One in a while there's a need for a no-op statement in C++. For example when implementing assert()
which is disabled in non-debug configuration (also see this question):
#ifdef _DEBUG
#define assert(x) if( !x ) { \
ThrowExcepion(__FILE__, __LINE__);\
} else {\
//noop here \
}
#else
#define assert(x) //noop here
#endif
So far I'm under impression that the right way is to use (void)0;
for a no-op:
(void)0;
however I suspect that it might trigger warnings on some compilers - something like C4555: expression has no effect; expected expression with side-effect
Visual C++ warning that is not emitted for this particular case but is emitted when there's no cast to void
.
Is it universally portable? Is there a better way?
The simplest no-op is just having no code at all:
#define noop
Then user code will have:
if (condition) noop; else do_something();
The alternative that you mention is also a no-op: (void)0;
, but if you are going to use that inside a macro, you should leave the ;
aside for the caller to add:
#define noop (void)0
if (condition) noop; else do_something();
(If ;
was part of the macro, then there would be an extra ;
there)