Let's say we have:
enum X {
X1,
X2,
X3
};
int func() {
std::map<int, X> abc;
...
}
Assume 0 is the key that is not in the container.
I know abc[0] needs to value-initialize the X object.
Here are the questions:
(1) Will the initialization always be zero-initialization for enumerations? namely abc[0] is always initialized as the enumerator corresponding to 0?
(2) What if we have
enum X {
X1 = 1,
...
What will abc[0] be?
Rule description. The default value of an uninitialized enumeration, just like other value types, is zero. A non-flags-attributed enumeration should define a member that has the value of zero so that the default value is a valid value of the enumeration.
A map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.
The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.
Will the initialization always be zero-initialization for enumerations? namely
abc[0]
is always initialized as the enumerator corresponding to0
?
Yes.
What if we have
enum X { X1 = 1, ...
What will
abc[0]
be?
It will be 0
.
Working program (also can be seen at http://ideone.com/RVOfT6):
#include <iostream>
#include <map>
enum X {
X1,
X2,
X3
};
int main()
{
X x = {};
std::map<int, X> abc;
std::cout << x << std::endl;
std::cout << abc[0] << std::endl;
}
Output:
0 0
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