简体   繁体   中英

C macros, what's the meaning of ((void)0)?

Given the following code written according to the C99 standard:

#define LOW 1 
#define MEDIUM 2 
#define HIGH 3

#define LOGGING_LEVEL HIGH

#if LOGGING_LEVEL >= MEDIUM
#define LOG_MEDIUM(message) printf(message) 
#else
#define LOG_MEDIUM(message) ((void)0) 
#endif

void load_configuration() { 
//...
LOG_MEDIUM("Configuration loaded\n"); 
}

what's the purpose of ((void)0) I searched the web a lot but nothing found regarding this.

Plus, why didn't we wrote ; after using printf(message)

Main idea is to exclude all LOG_MEDIUM if the criteria was not meet. After compilation those calls will not affect functionality.

The void-cast fixes a compiler warning. Here's an analogous testcase:

int main(void)
{
        0; // generates "foo.c:3:2: warning: statement with no effect"
        (void)0;
        return 0;
}

and (using a script to add gcc's warning flags) you see a warning for the line without a cast:

$ gcc-stricter -c foo.c
foo.c: In function ‘main’:
foo.c:3:2: warning: statement with no effect [-Wunused-value]
  0;
  ^

The extra parentheses and lack of semicolon allow the macro's result to be used interchangeably with the printf .

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