12

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?

Nathanael Demacon
  • 1,169
  • 7
  • 19
Denis
  • 2,786
  • 1
  • 14
  • 29

1 Answers1

11

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • What is the reason to not forbid that declaration? Any complications in grammar parsing for compilers? – Denis Sep 25 '19 at 15:19
  • 1
    @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. – StoryTeller - Unslander Monica Sep 25 '19 at 15:22
  • So does that also mean that functions defined as `static inline` are a thing of the past when it comes to modern C++? – 303 Dec 02 '21 at 16:26
  • @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. – StoryTeller - Unslander Monica Dec 02 '21 at 16:39