This is my small program:
enum Type
{
b = 1,
c = 2
};
int main()
{
Type b = b;
std::cout << b << std::endl;
return 0;
}
Which outputs 0. Can I conclude that the above definition consists of this sequential steps?
b
as variable of type Type
0
default valueAnd, do variables get initialized with 0 always, even if they are explicitly initialized?
My second question is - if it uses the variable in it's initialization list in specified example, why then I don't get error about ambiguity? Is compiler trying to find b
in the variable list first, and only then checks for declared enumeration?
You MUST assign an initial value into a constant variable when it is declared. If you do not place this initial value, C++ will not allow you to assign a value at a later time. Constants cannot be changed within a program.
For a variable, a definition is a declaration which allocates storage for that variable. Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it.
Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.
To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
Step 1 is correct, but the rest is wrong. What happens is that the variable b
is defined and immediately initialized to the value of the variable b
. This leads to undefined behavior because b
is not initialized before it's used in its own initialization.
If you want to initialize it to Type::b
then you need to explicitly write that:
Type b = Type::b;
Although the variable is considered defined during its own initialization, it is still illegal to evaluate it unit its initialization is complete. That is why Type b = b
is undefined behavior.
The reason why the variable is even defined is so that you could do this:
struct X {
int *p;
int a;
};
X x = {&x.a, 123};
cout << *x.p << endl;
Using the variable being initialized for purposes other than its own evaluation is legal. In the example above, the initializer of x
must be able to refer to x
in order to compute the address of its a
member. This is legal, because a
itself is not evaluated (demo).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With