Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map default value for enums

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?

like image 944
user3277360 Avatar asked Apr 22 '15 21:04

user3277360


People also ask

What is the default value for an enum?

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.

What is the default value of a map in C++?

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.

Where should enums be defined C++?

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.


1 Answers

Will the initialization always be zero-initialization for enumerations? namely abc[0] is always initialized as the enumerator corresponding to 0?

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
like image 188
R Sahu Avatar answered Nov 01 '22 13:11

R Sahu