Inline functions vs Preprocessor macros

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

How does an inline function differ from a preprocessor macro?

14条回答
  •  鱼传尺愫
    2020-11-22 13:30

    The Inline function are expanded by the compiler where as the macros are expanded by the Preprocessor, which is mere textual substitution.Hence

    • There is no type checking during macro invocation while type checking is done during function call.

    • Undesired results and inefficiency may occur during macro expansion due to reevaluation of arguments and order of operations. For example

      #define MAX(a,b) ((a)>(b) ? (a) : (b))
      int i = 5, j = MAX(i++, 0);
      

      would result in

      int i = 5, j = ((i++)>(0) ? (i++) : (0));
      
    • The macro arguments are not evaluated before macro expansion

      #define MUL(a, b) a*b
      int main()
      {
        // The macro is expended as 2 + 3 * 3 + 5, not as 5*8
        printf("%d", MUL(2+3, 3+5));
       return 0;
      }
      // Output: 16`
      
    • The return keyword cannot be used in macros to return values as in the case of functions.

    • Inline functions can be overloaded

    • The tokens passed to macros can be concatenated using operator ## called Token-Pasting operator .

    • Macros are generally used for code reuse where as inline functions are used to eliminate the time overhead (excess time) during function call(avoiding a jump to a subroutine).

提交回复
热议问题