Saturday, 9 May 2015

[ C++ ] WHAT IS THE DIFFERENCE BETWEEN INLINE FUNCTIONS AND MACROS?

Both Inline function  and Macro works the same in almost all scenarios there  are lot of key difference between them.
Before we get into those topics what is this inline and macro actually?
They are kind of like functions but instead of control passing which happens in functions these will replace the actual line of call by the function body..

for example

--------------------------------------------------------------------------------------------------------------------------

MACRO:

    #define MAX(x,y) x>y?x:y

would give the largest among 2 parameters on the call of  MAX(a,b)

If we are to write 
                  
                          int j=MAX(2,3);

  The preprocessor would replace the statement as
                           
                           int j=3;
before execution


INLINE:



inline int add(int a, int b)

    {

    return (a+b);
    
      }



after compiling the code each and every call of this function add in the program is replaced by the body of function


coming back to our topic



WHAT IS THE DIFFERENCE BETWEEN  INLINE FUNCTIONS AND MACROS?


     1.WAY OF HANDLING
                                                           Inline functions are parsed by the                     compiler, whereas macros are expanded by the C++ preprocessor.

          2.INCREMENT AND DECREMENTED:
                                                        Macros cannot properly handle increment and decrement operation as parameters in some cases, because it will not replace the variable by actual value of the operation instead it will replace each occurrence of the variable with appended operation 
           3.BRACES HANDLING:
                                                       macros cannot be used in paces where there is a macro call inside non braced statement (statement without braces because its a single lined one) because that would result in lifting out of statements after the first line of code in the macro definition

           eg:



                  #define ADD_TWO(x,y) x += 2; y +=2

                     bool flag = true;
                     int j = 5, k = 7;


                   if(flag)
                       ADD_TWO(j,k);
                

would work like


                           if(flag)

                           {

                                j +=2;

                             }
                            k +=2;
                    

No comments:

Post a Comment