Home > Software engineering >  Why does the compiler leave that decision up to us in c programming?
Why does the compiler leave that decision up to us in c programming?

Time:03-16

If the compiler automatically decides whether to do inline expansion or not, why and where do we use or should we use inline keywords where we see fit in c programming?

CodePudding user response:

Only advanced compilers are sophisticated enough to determine whether to inline functions automatically. clang and gcc do it either at compile time or at link time but older compilers did not and it was useful for savvy programmers to specify which functions to expand inline. Note however that the inline keyword is only a hint for the compiler, there is no obligation for the compiler to actually inline the code at all call sites. Note also that even savvy programmers make mistakes and incorrect assumptions. The urge for premature optimisation is a very common flaw.

The same remark applies to the register keyword: modern compilers are smart enough to determine which variables to store in CPU registers and when, but early C compilers did not and programmers could specify which variables to store in CPU registers. Again this was only a hint, which is now completely ignored in most cases.

Unless you are targeting very specific systems with older tool chains, you should just omit these keywords from your programs and let the compiler optimize the code. Do specify an optimisation option, such as -O2 or more and do enable all warnings with -Wall -Wextra -Werror to catch silly mistakes.

If you write libraries, there is a good use case for inline: you can define functions in header files tagged as static inline so they are only compiled if the source file actually uses them. Whether they will be actually inlined or not is still a compiler decision but if these functions are simple routines, it makes sense to define them this way in the header file as opposed to declaring a prototype and providing an implementation in a library.

It is actually a current trend to design libraries as a single header file containing the code for all functionality as static inline functions.

  •  Tags:  
  • c
  • Related