Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any sense to declare static global variable as inline?

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?

like image 806
Denis Avatar asked Sep 25 '19 14:09

Denis


People also ask

Does static inline make sense?

Thus such a function acts like any other static function and the keyword inline has no importance anymore, it becomes redundant. So, Practically marking a function static and inline both has no use at all.

Can we declare static variable as global?

A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.

Are static global variables bad?

The biggest problem with a global variable is that it is global, so anyone can access and modify it at any time. That problem is immensely reduced with a static variable, because all code accessing and modifying the variable is in that one file, and hopefully under your control.

Should I use static global variables?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.


1 Answers

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.

like image 152
StoryTeller - Unslander Monica Avatar answered Sep 29 '22 19:09

StoryTeller - Unslander Monica