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)
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:
- There is a time critical function.
- That is called often.
- Its small. Remember that inline functions take more space than normal functions. Some typical reasons why inlining is sometimes not done are:
- The function calls itself, that is, is recursive.
- The function contains loops such as for(;;) or while().
- 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 */