Are variables taken into account when calculating their initialization values?

This is my little program:

enum Type { b = 1, c = 2 }; int main() { Type b = b; std::cout << b << std::endl; return 0; } 

What are the outputs 0. Can I conclude that the above definition consists of the following steps:

  • Declaring b as a Type variable
  • Defining this variable and initializing with 0 default
  • Evaluation of its new value, which includes the variable itself (with a value of 0)
  • The purpose of this new value is a variable.

And, are variables always initialized with 0, even if they are explicitly initialized?

My second question is: if it uses the variable in it the initialization list in the specified example, why then I do not get an ambiguity error? Does the compiler try to find b in the variable list first and only then check the declared enum?

+5
source share
2 answers

Step 1 is correct, but everything else is wrong. It happens that the variable b defined and immediately initialized with the value of the variable b . This leads to undefined behavior because b not initialized until it is used in its own initialization.

If you want to initialize it to Type::b , you need to explicitly write the following:

 Type b = Type::b; 
+7
source

Although a variable is considered defined during its own initialization, it is still illegal to evaluate its unit, its initialization is complete. This is why Type b = b is undefined behavior.

The reason the variable is even defined is because you can do this:

 struct X { int *p; int a; }; X x = {&x.a, 123}; cout << *xp << endl; 

The use of a variable initialized for purposes other than one's own assessment is legal. In the above example, the initializer x must be able to refer to x in order to calculate the address of its member a . This is legal because a itself is not evaluated ( demonstration ).

+1
source

All Articles