I have read about inline
variables here and here but both links fail to mention whether an inline
variables are inline in sense that they could be inlined by the compiler just like inline functions. that is replaced with the actual value on call site.
I know inline variables have external linkage and unique address, but are they inlined like functions? does that property apply to inline variables?
both links fail to mention whether an
inline
variables are inline in sense that they could be inlined by the compiler just like inline functions.
Most likely that is because there is no reason to mention such a thing. You are basing your expectation on a false premise. The inline
keyword has no bearing on whether or not a function can be inlined by the compiler. A compiler can choose to inline functions not marked inline
, and it can choose to not inline functions marked inline
. This has been the case from the beginning, even when the inline
keyword was first introduced.
There was a time when the inline
keyword was a hint to the compiler, but even then it was only a hint. The compiler was always free to make its own decisions about which functions to inline. Since that time, compilers have become better than programmers when it comes to deciding which functions are efficient to inline. So most modern compilers ignore the supposed hint (at full optimization).
that is replaced with the actual value on call site.
This cannot be done in general. A function call can be replaced by the function's content (its body) by the compiler because the compiler knows what the function's content is. In contrast, a variable's content (its value) is not known by the compiler. That is, after all, often the point of declaring a variable. Since the compiler does not know the "actual value", there is no way for the compiler to use that value as a replacement for fetching the value from the variable's location in memory.
This can be done, though, in the specific case where the compiler can deduce what the value of the variable will be. As with functions, it is up to the compiler to decide whether to use that value directly in the machine instructions or to retrieve that value from the variable's memory location. The use of keywords has no bearing on this decision (although at full optimizations, I would expect the value to be used as long as it fits in a register). The only keyword that is relevant is constexpr
, which makes it much easier for the compiler to deduce what the value of the variable will be.