conditional expansion of a macro

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vivekgarg
    New Member
    • Oct 2008
    • 2

    conditional expansion of a macro

    Hi,
    Can I use some conditional operator to select a part of code to be expanded.
    What I meant was... Can I do something like this..

    #define func(arg1) \
    if arg1 == abc\ \* this line should not expand but just test*\
    some code\
    else\ \* this line should not expand but just test*\
    some other code


    Thanks
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    The macro will be replaced by its definition (after suitable argument replacement), so consider whether the expanded code is what you want to see there.

    A common concern with conditional code is what happens if it is invoked from within another conditional block. For example:
    Code:
    #define demo(arg) if (arg > 0) blink()
    if (this < that)
       demo(that);
    else
       demo(this);
    [I]... expands to ...[/I]
    if (this < that)
       if (that > 0) blink();
    else
       if (this > 0) blink();
    Notice that the 'else' ends up being associated with if(that>0) instead of if(this<that) as you would have expected from reading the source code.

    The typical idiom used to prevent this from happening is to encapsulate any multi-line macro definition as follows:
    Code:
    #define demo(arg) \
    do { \
    if (arg > 0) blink(); \
    } while(0)
    Notice that all of the source lines of the macro definition are enclosed within a set of braces, making them act like a single instruction. This prevents the else confusion described above; it also prevents you from falling out early if the macro is invoked within a non-bracketed if statement.
    Notice that there is no semi-colon after while(0). This forces the programmer to terminate the macro invocation with a semi-colon.

    Comment

    • vivekgarg
      New Member
      • Oct 2008
      • 2

      #3
      Yeah Donbock what you said was certainly correct in it's own context but I guess I was not clear enough in my question.
      Basically what I am asking is, why this peice of code dosen't work and what is the possible solution.

      #ifdef ABC
      #define TEST /
      cout<<"abc"
      #else
      #define TEST
      cout<<"xyz"
      #endif

      int main()
      {
      TEST;
      #define ABC
      TEST
      #undef ABC
      TEST
      return 0;
      }
      =============
      Output:xyzxyzyx z

      Thanks

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        That's the way cpp (the C Macro PreProcessor) works: (re)defining ABC after
        macro TEST has been defined doesn't (re)define macro TEST. A macro processor
        simply runs through text, from top to bottom, and it does what it has to do.

        kind regards,

        Jos

        Comment

        Working...