Function-like macros and strange behavior

前端 未结 2 1119
南方客
南方客 2021-01-20 17:08

I have started reading Effective C++ and at some point in item 2, the following is mentioned:

// call f with the maximum of a and b
#define CALL_WITH_MAX(a,          


        
2条回答
  •  余生分开走
    2021-01-20 18: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.

提交回复
热议问题