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

2019-01-09 08:49发布

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.

9条回答
混吃等死
2楼-- · 2019-01-09 09:25

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.

查看更多
够拽才男人
3楼-- · 2019-01-09 09:27

As this is a macro, you should also consider a case like

if (other_cond)
    conditional_noop(123);

to be on the safe side, you can give an empty statement like

#define conditional_noop(X) {}

for older C sometimes you need to define the empty statment this way (should also get optimized away):

#define conditional_noop(X) do {} while(0)
查看更多
叼着烟拽天下
4楼-- · 2019-01-09 09:34

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).

查看更多
登录 后发表回答