简体   繁体   中英

C++ Directive With void(0)

What is the purpose of having a directive like below?

#define TEST_CONDITION(con) !(con) ? (void)0:

In particular, I see this called at the start of other directives.

For example,

#define OTHER_CONDITION(..)
  TEST_CONDITION(someFunction)
  ANOTHER_DIRECTIVE(...)

Doesn't TEST_CONDITION just no-op or a boolean is returned that isn't used in these cases?

Expand the macro, and it becomes clearer. I'll also use some formatting to keep the code readable, and I assume that the lack of some essential escape characters is not meant to be part of the example. OTHER_CONDITION becomes:

!(someFunction)
    ? (void)0
    : ANOTHER_DIRECTIVE(...)

So, the expression someFunction is executed, and if it is true , then ANOTHER_DIRECTIVE(...) (or whatever it expands to) is executed. Otherwise nothing is executed.


Simpler way to write OTHER_CONDITION could be:

#define OTHER_CONDITION(..) if(someFunction) ANOTHER_DIRECTIVE(...)

This simplification lacks some restrictions that TEST_CONDITION provides:

  • TEST_CONDITION makes it impossible to append an else branch.
  • TEST_CONDITION makes it ill-formed to use a non-void ANOTHER_DIRECTIVE(...) .

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