Function-like macros and strange behavior

泪湿孤枕 提交于 2019-12-01 22:42:39

The compiler replaces the macros with exactly what you pass in, verbatim. So you end up with

int a = 5, b = 0;
f((++a) > (b) ? (++a) : (b));
f((++a) > (b+10) ? (++a) : (b+10));

Use g++ -E myprog.cpp (replace g++ with whatever-your-compiler-is if you are not using g++) - it works on ALMOST all compilers, it will produce the actual stuff after preprocessing.

And this is a great example of why you shouldn't use macros to do function-type stuff.

You'd get much more of what you (probably) expect if you were to use an inline function:

 inline void CallWithMax(int a, int b) 
 {
     f((a) > (b) ? (a) : (b));
 }

Any decent compiler should be able to do this AT LEAST as efficient as a macro, with the added advantage that your a and b are evaluated once in the calling code, and nothing "weird" happens.

You can also step through a inline function if you build your code with debug symbols, so if you want to see what value a and b actually are inside the function, you can do that. Macros, because they expand into the original place in the source code, so you can't really see what's going on inside.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!