Is a variable a default value?

The question is simple:

#include <iostream> enum SomeEnum { EValue1 = 1, EValue2 = 4 }; int main() { SomeEnum enummy; std::cout << (int)enummy; } 

What will be the way out?

Note. This is not an interview, this is the code I inherited from previous developers. The streaming operator here, for example, takes place, for example, the actual inherited code does not have it.

+43
c ++ variables enums default-value
Jul 27 '11 at 10:23
source share
2 answers

Playing Undefined Behavior . The value of enummy is undefined. Conceptually, there is no difference between your code and the following code:

 int main() { int i; //indeterminate value std::cout << i; //undefined behavior }; 

If you defined your variable in the namespace scope, this will be initialized to 0.

 enum SomeEnum { EValue1 = 1, EValue2 = 4, }; SomeEnum e; // e is 0 int i; // i is 0 int main() { cout << e << " " << i; //prints 0 0 } 

Do not be surprised that e may have values โ€‹โ€‹different from any values โ€‹โ€‹of the SomeEnum enumerator. Each enumeration type has a basic integral type (for example, int , short or long ), and the set of possible values โ€‹โ€‹of an object of this enumeration type is a set of values โ€‹โ€‹that has a basic integral type. Enum is just a way to conveniently name some of the values โ€‹โ€‹and create a new type, but you do not limit the values โ€‹โ€‹of your enumeration to the set of counter values.

Update: Some quotes supporting me:

For zero initialization of an object of type T means:
- if T is a scalar type (3.9), the object is set equal to 0 (zero), converted to T;

Note that enums are scalar types.

To initialize an object of type T means:
- if T - class type blah blah
- if T is a nonunit class, the type of blah blah
- if T is an array type, then blah blah - otherwise the object is initialized to zero

So, we get to another part. And the namespace scope objects are initialized with a value

+38
Jul 27 '11 at 10:24
source share

The output will be uncertain. enummy member variables can only be 1 or 4.

-one
Sep 05 '13 at 13:03 on
source share



All Articles