14

Consider, global variable (not static class member!) is declared in the header file:

inline static int i{}; 

It is valid construction for several compilers that I tested, and experiments demonstrate that several distinct objects will be created in different translation units, although it is also declared as inline (it means that only one instance of that variable must exist in the program). So, has static keyword more priority than inline in that case?

1 Answer 1

13

So, has static keyword more priority than inline in that case?

Pretty much. static has an effect that interferes with inline. The C++ standard states that

... An inline function or variable with external linkage shall have the same address in all translation units.

And the static qualifier imposes internal linkage, so the single address guarantee does not have to hold. Now, a name with internal linkage in different translation units is meant to denote different object in each TU, so getting multiple distinct i's is intended.

All in all, the static negates the inline. And there is no point to having a static inline variable over a plain static one.

Sign up to request clarification or add additional context in comments.

7 Comments

What is the reason to not forbid that declaration? Any complications in grammar parsing for compilers?
@user3514538 - No. Probably no one considered it an actual problem when first adding it. And it isn't some huge problem that warrants the standardization process now.
So does that also mean that functions defined as static inline are a thing of the past when it comes to modern C++?
@303 - static inline is a C artefact, born out of the different way C treats functions declared inline. C++ always treated inline functions the way I described here.
@LouisGo - I don't see why it would be more efficient. In all arches I know, all those constants will be parked in the same section of the executable ("in a TU" is only relevant to source code locality and access), and each will need to be initialized dynamically along with allocation. Might as well have just one (by ditching the static).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.