Anton Daneyko Anton Daneyko - 1 month ago 8
C Question

How do I implement no-op macro (or template) in C++?

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.

Answer

As mentioned before - nothing.
Also, there is a misprint in your code.
it should be #else not #elif. if it is #elif it is to be followed by the new condition

#include <iostream>   

#ifdef NOOP       
    #define conditional_noop(x) do {} while(0)
#else       
    #define conditional_noop(x) std::cout << (x)   
#endif  

Have fun coding! EDIT: added the [do] construct for robustness as suggested in another answer.

Comments