Global declarations / initializations using static, const, constexpr

In C ++ or C ++ 11 for the following // initialization declarations

// global scope const int a = 1; // line 1 static const int b = 2; // line 2 constexpr int c = 3; // line 3 static constexpr int d = 4; // line 4 constexpr int e = a + b + c*d; // line 5 static constexpr int f = a - b - c*d; // line 6 

This question says that in the file area there is no difference between lines 1 and 2 in C ++. What about lines 3 and 4?

Are there any differences between lines 4 and 5?

Are there any differences between lines 5 and 6?

+2
c ++ c ++ 11
source share
2 answers

No, there should not be any difference (except for their values, of course), because constexpr and const imply an internal relationship:

[C++11: 3.5/3]: name with a namespace scope (3.3.6) has an internal relationship if it is a name

  • a template for a variable, function, or function that is explicitly declared static ; or,
  • a variable that is explicitly declared const or constexpr , and not declared explicitly extern , but previously declared to have an external binding ; or
  • Anonymous union data member.
+4
source share

static there are variables for the lifetime of a static program useful for such functions:

 void func (int i) { int var = i; } 

when a function finishes executing its code, its objects are automatically destroyed to prevent this, you can use static

 void func (int i) { static int var = i; } 

this means that when the function finishes executing its code, the object defined as static will remain until the program finishes

const is applied to variables and does not allow them to change your code. and constexpr are used for constant expressions, these two are read-only, this means that after initialization the values ​​cannot be changed

the difference of these two:

 static constexpr int d = 4; // line 4 constexpr int e = a + b + c*d; 

in static constexpr int d = 4 we define a variable called d, which is a constant of an integer constant expression and has a value of 4 and cannot be changed and remains until the program finishes

and in constexpr int e = a + b + c*d; we define the name of the variable e, which constant expression integer, which has a value, depends on the result in these operations and cannot be changed

0
source share

All Articles