Inline functions vs Preprocessor macros

后端 未结 14 2305
一个人的身影
一个人的身影 2020-11-22 12:37

How does an inline function differ from a preprocessor macro?

14条回答
  •  天涯浪人
    2020-11-22 13:32

    In GCC (I'm not sure about others), declaring a function inline, is just a hint to the compiler. It is still up to the compiler at the end of the day to decide whether or not it includes the body of the function whenever it is called.

    The difference between in-line functions and preprocessor macros is relatively large. Preprocessor macros are just text replacement at the end of the day. You give up a lot of the ability for the compiler to perform checking on type checking on the arguments and return type. Evaluation of the arguments is much different (if the expressions you pass into the functions have side-effects you'll have a very fun time debugging). There are subtle differences about where functions and macros can be used. For example if I had:

    #define MACRO_FUNC(X) ...
    

    Where MACRO_FUNC obviously defines the body of the function. Special care needs to be taken so it runs correctly in all cases a function can be used, for example a poorly written MACRO_FUNC would cause an error in

    if(MACRO_FUNC(y)) {
     ...body
    }
    

    A normal function could be used with no problem there.

提交回复
热议问题