Inline functions vs Preprocessor macros

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

How does an inline function differ from a preprocessor macro?

14条回答
  •  星月不相逢
    2020-11-22 13:26

    #include
    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<

    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.

提交回复
热议问题