Q46 What is difference between inline function, C macro and constant?

Inline Function – The inline keyword put before a function makes it inline function. Inline keyword is used to make a request to the compiler to copy the code into the object at every place the function is called. That is, the function is expanded at each point of call. Most of the advantage of inline functions comes from avoiding the overhead of calling an actual function. Such overhead includes saving registers, setting up stack frames, and so on. But with large functions the overhead becomes less important. Inlining tends to blow up the size of code, because the function is expanded at each point of call. But note that the inline functions are non-standard C. They are provided as compiler extensions.

int func(int x)

{

}

inline int func(int x)

{

}

Macro –

Inlined functions are not the fastest, but they are the kind of better than macros (which people use normally to write small functions).The problem with macros is that the code is literally copied into the location it was called from. So if the user passes a “double” instead of an “int” then problems could occur. However, if this scenario happens with an inline function the compiler will complain about incompatible types. This will save you debugging time stage.

Good time to use inline functions is:

  1. There is a time critical function.
  2. That is called often.
  3. Its small. Remember that inline functions take more space than normal functions. Some typical reasons why inlining is sometimes not done are:
  4. The function calls itself, that is, is recursive.
  5. The function contains loops such as for(;;) or while().
  6. The function size is too large.

Constant – The word meaning itself says, A variable or value which cannot be modify or changed is called constant.

int const  *num = 100; /* Here num is a pointer to const integer */

++(*num);  /* Illegal operation, the value of num cannot modify */

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.