How do I implement no-op macro in C++?
#include
#ifdef NOOP
#define conditional_noop(x) what goes here?
#else
#
#ifdef NOOP
static inline void conditional_noop(int x) { }
#else
static inline void conditional_noop(int x) { std::cout << x; }
#endif
Using inline function void enables type checking, even when NOOP
isn't defined. So when NOOP
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 the NOOP
flag on.
You can just leave it blank. You don't need to follow the #define
with anything.
While leaving it blank is the obvious option, I'd go with
#define conditional_noop(x) do {} while(0)
This trick is obviously no-op, but forces you to write a semicolon after conditional_noop(123)
.
Defining the macro to be void
conveys your intent well.
#ifdef NOOP
#define conditional_noop(x) (void)0
#else
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:
#ifdef NOOP
#define conditional_noop(x) (void)0
#else
#define conditional_noop(x) std::cout << (x); (void)0
#endif
In C++, (void)0
does nothing. This article explains other not-as-good options, as well as the rationale behind them.
I think that a combination of the previous variants is a good solution:
#ifdef NOOP
static inline void conditional_noop(int x) do {} while(0)
#else
static inline void conditional_noop(int x) do { std::cout << x; } while(0)
#endif
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.