What are the requirement for a function so it could be executed inline in C++? Is there a case that a function can't be inlined, or can any function be inlined and it is the responsibility of the programmer to decide how to define the function, based on run time and compilation-time considerations?
what are the requirement for a function so it could be executed inline in c++?
It needs to be defined at every spot in which it's called (typically this is done by putting it in a .h
).
is there a case that a function can't be inline?
Not in terms of the language standard, I believe, although of course each compiler can and will implement some restrictions of its own.
or any function can be inline and it is the responsibility of the programmer to decide how to define the function, based on run time and compilation-time considerations?
The inline
keyword is just a hint from the programmer to the compiler that the programmer would really like this function to be inlined (presumably the programmer has spotted substantial call overhead with a small function being called in "hot" loops as shown by the profiler -- or, the function is so tiny that it's about as small as the calling code;-) -- or, inlining the function allows "optimization across function boundaries" that a particular compiler can't spot or can't perform otherwise -- and so forth).
The compiler is free to ignore the hint just as it's free to ignore the older register
hint for a variable's storage class (I believe nowadays most optimizing C++ compilers do ignore register
but fewer ignore inline
) -- IOW, the compiler is free to inline all or some of the calls to a function whether that function is declared inline
or not.
(Of course it won't "inline calls" when they're done through an explicit pointer to the function that is stashed away at some points and used at others, or when the function's address is passed as a parameter to some other function - but that might affect the inlining of specific calls, not necessarily other calls to the same function that are done differently).
"Just in case" your compiler takes your inline
hints very earnestly, it's often worth measuring code size and speed with and without inline
around (unless your compiler offers an option/flag for the purpose, just a #define inline
will definitely "disable" the effect of inline
and thereby allow such measurement). But if you're going to deploy your code across multiple compilers, esp. for multiple architectures, be aware that the effects that are positive on one platform may end up being counterproductive on another, given the difference in compilers' optimizaiton strategies and in CPU architectures.