Introduction

Save the below code in a file named enum.c and try to compile it using the following command: gcc enum.c -o enum && ./enum. This will give the following error:

enum.c:8:3: error: overflow in enumeration values
   _4
   ^
enum.c: In function ‘main’:
enum.c:11:48: error: ‘FourBytes’ undeclared (first use in this function)
   printf("sizeof(FourBytes)=%d\n", (int)sizeof(FourBytes));
                                                ^
enum.c:11:48: note: each undeclared identifier is reported only once for each function it appears in
enum.c:12:49: error: ‘EightBytes’ undeclared (first use in this function)
   printf("sizeof(EightBytes)=%d\n", (int)sizeof(EightBytes));

However, if you save this same code as enum.cpp and compile it as: g++ enum.cpp -o enum && ./enum. This will compile successfully and gives the following output!

sizeof(FourBytes)=4
sizeof(EightBytes)=8

Yes! The C++ compiler automatically takes care of overflows by 'upgrading' the enum to be of 8 bytes!

Code

#include <stdio.h>
enum FourBytes {
  _1,
  _2
};
enum EightBytes {
  _3 = 0xffffffff,
  _4
};
int main(int argc, char** argv) {
  printf("sizeof(FourBytes)=%d\n", (int)sizeof(FourBytes));
  printf("sizeof(EightBytes)=%d\n", (int)sizeof(EightBytes));
  return 0;
}