Monday, March 21, 2016

Difference between macros and inline functions

Difference between macros and inline functions
1) macros are text replacement. The macro will be expanded in preprocessing time, but inline functions are replaced during compile time. They are just normal functions.
2) macros have following problems
    a) There is no typechecking for macro arguments
    b) Macros results ambiguity if properly not created.
        # define product(a) a*a
        will cause wrong result when called
        result = product(++a) if a = 10
        This will expand to
        product(++10) (++10*++10) = 120 but actually expected is
        a = 10
        result = product(++10) i.e 11
        result = 121
    c) One more problem if multiple statements
    #define multi(a,b) a+=10; b+=20
    if the above macro called within if statement
    if (flag){
        multi(a,b)
    }
    will become
    if (flag){
        a+=10;
    }
    b += 20 ;
3) All above problems will not occur when inline functions are used
4) Since macros are expanded in preprocessing time, there wont be any symbols available for debugger
5) With inline functions you can easily debug functions.

Caution: One of the important thing to know about MACRO.. :-(
#define INIT_LIST_HEAD(ptr) do {
    (ptr)->next = (ptr) ; \
    (ptr)->prev = (ptr) ; \
    } while (0)
If there is no do while then the following is invalid
if (foo)
    INTI_LIST_HEAD(ptr)
to
if (foo)
    (ptr)->next = (ptr) ;
    (ptr)->prev = (ptr) ;
   
but if do while is present then
if (foo)
    do {
        (ptr)->next = (ptr) ;
        (ptr)->prev = (ptr) ;
    while (0)
The above is valid

No comments:

Post a Comment