1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Vancouver, Canada
    Rep Power

    Visual Studio won't be able to compile MACRO function with local variable?

    Hi, geeks:

    It seems Visual Studio is not able to build the following MACRO with a new local variable

    #define FAST_SCALE_PQ(X,P,Q) ({						\
       unsigned __x = (X);							\
       func1( __x * (P), __x, __x, (Q) );				\
    GCC seems to work fine. I also tested
    #define TEST_FAST_SCALE_PQ(X,P,Q)   \
        func( ( (X) * (P) ), (X), (X), (Q) );
    still wrong.

    Any work around?

    Thank you very much.

    Best Regards
  2. #2
  3. Contributing User

    Join Date
    Aug 2003
    Rep Power
    It won't compile because the syntax is incorrect. The statment expression you are attempting to use is a GNU C extension and not ISO C.

    When this macro is used in code it will be replaced with a code block surrounded in parentheses, which is not valid C code syntax.
    If you must use a macro then a well formed implementation would look as follows:
    #define FAST_SCALE_PQ(X,P,Q) do{ \
        unsigned __x = (X); \
        func1( __x * (P), __x, __x, (Q) ); \
    } while(0)
    However if the macro is expected to return a value, that will not work, and you should use a function instead.

    The do...while(0) dummy loop is necessary to avoid other syntax problems (see here for example).

    There is little advantage in using a macro in this case, and many reasons for not doing so (and you have found one of them!). In this case if all you want to do is simplify the interface to func1(), then a wrapper function would be more appropriate, easier to debug, maintain, and understand.
    Last edited by clifford; February 4th, 2012 at 04:07 AM.
  4. #3
  5. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Rep Power
    I believe double leading underscores are reserved for the compiler writer.

    Comments on this post

    • clifford agrees : Indeed; though few compilers would enforce it; its just a bad idea nonetheless.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

IMN logo majestic logo threadwatch logo seochat tools logo