How do I implement no-op macro in C++?
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) what goes here?
#else
#define conditional_noop(x) std::cout << (x)
#endif
int main() {
conditional_noop(123);
}
I want this to do nothing when NOOP is defined and print "123", when NOOP is not defined.
You can just leave it blank. You don't need to follow the
#define
with anything.nothing!
Defining the macro to be
void
conveys your intent well.Like others have said, leave it blank.
A trick you should use is to add
(void)0
to the macro, forcing users to add a semicolon after it:In C++,
(void)0
does nothing. This article explains other not-as-good options, as well as the rationale behind them.Using inline function void enables type checking, even when
NOOP
isn't defined. So whenNOOP
isn't defined, you still won't be able to pass a struct to that function, or an undefined variable. This will eventually prevent you from getting compiler errors when you turn theNOOP
flag on.I think that a combination of the previous variants is a good solution:
The good thing is that these two codes differ only inside a block, which means that their behaviour for the outside is completely identical for the parser.