Thread: Help with macros

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    147

    Help with macros

    I need help because what I want, I dont know if it is possible to do it with macros.

    I have:
    Code:
    #ifdef ESTADISTICAS
    #   define   S(x)  (x)
    #else
    #   define   S(x)
    #endif
    It is a macro to allow me to collect stats. Now I do something like:
    Code:
    S(++stats.cortes);
    But when I want something more complex like:
    Code:
    #ifdef ESTADISTICAS
    if (cont < 3) ++stats.move_hit[cont];
    #endif
    It takes me three lines of code. Is there any way to do it in a only one line? like:
    Code:
    S(if (cont < 3) ++stats.move_hit[cont]);
    Doing this way would allow me a more friendly code and more readable, in a single line, but when I compile I get an error "expected expression berore if".

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    It you want complicated things to appear as single statements, then perhaps this.
    Code:
    #ifdef ESTADISTICAS
    #   define   S(x)  do { \
        x                   \
        } while(0)
    #else
    #   define   S(x)
    #endif 
     
    int
    main(void)
    {
      struct {
        int move_hit[3];
      } stats;
      int cont = 0;
      S(if (cont < 3) ++stats.move_hit[cont];);
      return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2008
    Posts
    147
    Quote Originally Posted by Salem View Post
    It you want complicated things to appear as single statements, then perhaps this.
    Code:
    #ifdef ESTADISTICAS
    #   define   S(x)  do { \
        x                   \
        } while(0)
    #else
    #   define   S(x)
    #endif 
     
    int
    main(void)
    {
      struct {
        int move_hit[3];
      } stats;
      int cont = 0;
      S(if (cont < 3) ++stats.move_hit[cont];);
      return 0;
    }
    Thanks, it works perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C macros
    By rendezed in forum C Programming
    Replies: 4
    Last Post: 01-26-2011, 08:36 AM
  2. Macros inside of macros
    By Chewie8 in forum C Programming
    Replies: 2
    Last Post: 02-24-2008, 03:51 AM
  3. Macros
    By jsbeckton in forum C Programming
    Replies: 11
    Last Post: 12-02-2005, 02:10 AM
  4. Macros Using #s
    By Krak in forum C++ Programming
    Replies: 21
    Last Post: 07-18-2005, 01:03 AM
  5. macros
    By rpc2005 in forum C Programming
    Replies: 23
    Last Post: 06-14-2005, 08:56 AM

Tags for this Thread