Inline functions vs Preprocessor macros

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

How does an inline function differ from a preprocessor macro?

相关标签:
14条回答
  • 2020-11-22 13:22

    Preprocessor macros are just substitution patterns applied to your code. They can be used almost anywhere in your code because they are replaced with their expansions before any compilation starts.

    Inline functions are actual functions whose body is directly injected into their call site. They can only be used where a function call is appropriate.

    Now, as far as using macros vs. inline functions in a function-like context, be advised that:

    • Macros are not type safe, and can be expanded regardless of whether they are syntatically correct - the compile phase will report errors resulting from macro expansion problems.
    • Macros can be used in context where you don't expect, resulting in problems
    • Macros are more flexible, in that they can expand other macros - whereas inline functions don't necessarily do this.
    • Macros can result in side effects because of their expansion, since the input expressions are copied wherever they appear in the pattern.
    • Inline function are not always guaranteed to be inlined - some compilers only do this in release builds, or when they are specifically configured to do so. Also, in some cases inlining may not be possible.
    • Inline functions can provide scope for variables (particularly static ones), preprocessor macros can only do this in code blocks {...}, and static variables will not behave exactly the same way.
    0 讨论(0)
  • 2020-11-22 13:22

    To know the difference between macro and inline function ,firstly we should know what exactly they are and when we should use them.

    FUNCTIONS:

    int Square(int x){
    return(x*X);
    }
    int main()
    {
    int value = 5;
    int result = Square(value);
    cout << result << endl;
    }
    
    • Function calls have overhead associated with it, as after function finishes execution it has to know where it has to return and also need to store the value in stack memory.

    • For small applications it won't be a problem, but let's take an example of financial applications where thousands of transactions are happening every second, we can't go with function calls.

    MACROS:

    # define Square(x) x*x;
    int main()
    {
    int value = 5;
    int result = Square(value);
    cout << result << endl;
    }
    
    • Macros works at preprocessing stage i.e at this stage the statements written with # keyword will be replaced with the content i.e

    int result = Square(x*x)

    But macros has bugs associated with it.

    #define Square(x) x*x
    int main() {
        int val = 5;
        int result = Square(val + 1);
        cout << result << endl;
        return 0;
    }
    

    Here the output is 11 not 36.

    INLINE FUNCTIONS:

    inline int Square(int x) {
        return x * x;
    }
    
    int main() {
        using namespace std;
        int val = 5;
        int result = Square(val + 1);
        cout << result << endl;
        return 0;
    }
    

    Output 36

    Inline keyword requests the compiler to replace the function call with the body of the function , here the output is correct because it first evaluates the expression and then passed.It reduces the function call overhead as there is no need to store the return address and stack memory is not required for function arguments.

    Comparison Between Macros and Inline Functions:

    1. Macros works through substitution, whereas in inline Functions ,function call is replaced with the body.
    2. Macros are error prone due to substitution while inline functions are safe to use.
    3. Macros don't have address whereas inline functions has address.
    4. Macros are difficult to use with multiple lines of code, whereas inline functions are not.
    5. In C++ macros cannot be used with member functions whereas inline function could be.

    CONCLUSION:

    Inline functions are sometimes more useful than macros, as it improves the performance and is safe to use and reduced function call overhead too. It's just a request to the compiler, certain functions won't be inlined like:

    • large functions
    • functions having too many conditional arguments
    • recursive code and code with loops etc.

    which is a good thing, because that is whenever the compiler thinks it's best to do things another way.

    0 讨论(0)
  • 2020-11-22 13:25

    Macros are ignoring namespaces. And that makes them evil.

    0 讨论(0)
  • 2020-11-22 13:26
    #include<iostream>
    using namespace std;
    #define NUMBER 10 //macros are preprocessed while functions are not.
    int number()
    { 
        return 10;
    }
    /*In macros, no type checking(incompatible operand, etc.) is done and thus use of micros can lead to errors/side-effects in some cases. 
    However, this is not the case with functions.
    Also, macros do not check for compilation error (if any). Consider:- */
    #define CUBE(b) b*b*b
    int cube(int a)
    {
     return a*a*a;
    }
    int main()
    {
     cout<<NUMBER<<endl<<number()<<endl;
     cout<<CUBE(1+3); //Unexpected output 10
     cout<<endl<<cube(1+3);// As expected 64
     return 0;
    }
    

    Macros are typically faster than functions as they don’t involve actual function call overhead.

    Some Disadvantages of macros: There is no type checking.Difficult to debug as they cause simple replacement.Macro don’t have namespace, so a macro in one section of code can affect other section. Macros can cause side effects as shown in above CUBE() example.

    Macros are usually one liner. However, they can consist of more than one line.There are no such constraints in functions.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-22 13:31

    First, the preprocessor macros are just "copy paste" in the code before the compilation. So there is no type checking, and some side effects can appear

    For example, if you want to compare 2 values:

    #define max(a,b) ((a<b)?b:a)
    

    The side effects appear if you use max(a++,b++) for example (a or b will be incremented twice). Instead, use (for example)

    inline int max( int a, int b) { return ((a<b)?b:a); }
    
    0 讨论(0)
提交回复
热议问题