I do not understand the behaviour of #define macro in C++

后端 未结 4 1330
既然无缘
既然无缘 2021-01-29 14:09

I need to understand how this code works:

#define foo1( a ) (a * a)              // How does this work?
inline int foo2(         


        
相关标签:
4条回答
  • 2021-01-29 14:35

    The difference is, the foo1 defined by #define is NOT a function, while foo2 is.

    In compilation process, the compiler will replace the foo1(parameter) keyword in your code with (parameter * parameter).

    Meaning,

    cout << "foo1 = " << foo1( 1+2 ) << "\n"; // How does this work?

    will be replaced by the following code,

    cout << "foo1 = " << ( 1+2 * 1+2 ) << "\n"; // How does this work?

    (Because the parameter here is 1+2, instead of 3.)

    The result is 1+2 * 1+2, which is 5.

    Now let look at foo2, since it is an inline function, the compiler will not replace it. When your code is compiled into an executable file, and the executable file is executed, the 2 + 1 expression will be calculated first, and the result, 3, will then be passed to foo2().

    In conclusion, the difference really lies in the compilation of your code. You may need more knowledge on what happens there.

    0 讨论(0)
  • 2021-01-29 14:42

    Well, it's really simple.

    foo1( 1 + 2 )
    

    will turn into:

    ( 1 + 2 * 1 + 2 )
    

    which is actually:

    1 + 2 + 2 = 5
    

    This is how macros work.

    0 讨论(0)
  • 2021-01-29 14:55

    Macro is not a function. The compiler will expand all macros and then compile it. To see the expanded code, you can use the following command using -E option in gcc:

    gcc -E <source code> -o <preprocessed file name>
    

    Or in Visual C++, under Configuration Properties->C/C++->Preprocessor, set "Generate Preprocessed File".

    BTW, your macro is problematic. You should use

    #define foo1( a ) ((a) * (a))
    

    instead of

     #define foo1( a ) (a * a)
    
    0 讨论(0)
  • 2021-01-29 14:58

    Macros are not functions.

    Macros do TEXT replacement. So when you have

    #define foo1( a )   (a * a)
    

    any instance of foo1( ... ) with anything between then parenthesis will be expanded AS TEXT, not as an expression. So when you have foo1( 1 + 2 ) it turns into ( 1 + 2 * 1 + 2 )

    0 讨论(0)
提交回复
热议问题