When answering this question about enums I read the spec regarding the underlying size and it says (regarding unscoped enums) [7.5.5]:
If the underlying type is not fixed, the type of each enumerator is the type of its initializing value
But when I try the following code I get sizeof int for all enums (tested on g++, VC and clang).
#include <iostream>
using namespace std;
enum e1 { e1a };
enum class ec1 { ec1a };
enum e2 { e2a = 'a' }; // I expect this to have sizeof 1
enum class ec2 { ec2a = 'a' };
int main() {
cout << "plain enum:" << sizeof(e1a) << endl;
cout << "enum class:" << sizeof(ec1::ec1a) << endl;
cout << "char initialized plain enum:" << sizeof(e2a) << endl;
cout << "char initialized enum class:" << sizeof(ec2::ec2a) << endl;
}
Output:
plain enum: 4
enum class:4
char initialized plain enum: 4
char initialized enum class: 4
What did I misunderstand?
You missed this sentence:
Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration.
Proof:
#include <iostream>
using namespace std;
enum e1 { e1a };
enum class ec1 { ec1a };
enum e2 {
e2a = 'a' ,
e2b = sizeof(e2a) // <-- here the type of e2a is still char
};
// <-- here the type of e2a becomes the same as the type of e2 (i.e. int)
enum class ec2 { ec2a = 'a' };
int main() {
cout << "plain enum:" << sizeof(e1a) << endl;
cout << "enum class:" << sizeof(ec1::ec1a) << endl;
cout << "char initialized plain enum:" << sizeof(e2a) << " but e2b=" << e2b <<endl;
cout << "char initialized enum class:" << sizeof(ec2::ec2a) << endl;
}
Output:
plain enum:4
enum class:4
char initialized plain enum:4 but e2b=1
char initialized enum class:4
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