简体   繁体   中英

Syntax Error related to Macro in C

#include<conio.h>
#include <stdio.h>

#define small 0
#define big   1

#define dummy( _x_ )    \
( small > big ) ? ( printf _x_ ) : ( void( 0 ) )

int main() {  

    dummy( ( "Four is %d", 4 ) );
    getch();
    return 0; 
}

When I compiled above program in gcc, it is giving the error below:

error : expected ')' before numeric constant.

I am not understanding why I am getting it? To me it seems everything is correct. Please help.

The void(0) part is a syntax error. You try to call a function named void with a 0 argument. This will work:

( ( small > big ) ? printf _x_ : (void) 0 )

The problem seems to come from your void(0) . I can't even compile it as a valid C expression/statement.

int main()
{
    void(0);
    return 0;
}

Gives:

error: expected identifier or ‘(’ before numeric constant

Just replace void(0) with 0 . Ternary operator alternatives are supposed to have the same type anyway.

Jens gives you the solution, but seems that you need (void)printf in order to skip warning:

warning: ISO C forbids conditional expr with only one void side [-pedantic]

This works without warnings:

#define dummy( _x_ ) \
       (small > big) ? (void)printf _x_ : (void)0

On the other hand dummy( ( "Four is %d", 4 ) ); looks ugly to me, I suggest to use __VA_ARGS__ and skip double parenthesis in your function call:

#include <stdio.h>

#define small 0
#define big   1

#define dummy(...) \
     (small > big) ? (void)printf(__VA_ARGS__) : (void)0

int main(void)
{  
    dummy("Four is %d", 4);
    return 0; 
}

Or don't pass params:

#include <stdio.h>

#define small 0
#define big   1

#define dummy (!(small > big)) ? (void)0 : (void)printf

int main(void)
{  
    dummy("Four is %d", 4);
    return 0; 
}

After the macro replacements your code changed like this-

int main() {

( 0 > 1 ) ? ( printf ( "Four is %d", 4 ) ) : ( void( 0 ) );
return 0;
}

Here the compiler doesn't know what is void( 0 ) . It is not a valid syntax in C. So try to replace it by some other statement.

Try the following code

#define dummy( _x_ )    \
( small > big ) ? ( printf _x_ ) : (printf("Conditon fails!\n"))

or

#define dummy( _x_ )    \
( small > big ) ? ( printf _x_ ) : ((void) 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM