1
#include <stdio.h>

enum {AA, BB, CC} s;

int main()
{
s = 4;
printf("%d\n",s);
return 0;
}

The compiler doesn't give any warning and prints 4. What is happening behind the scene? Is s treated as an int type?

Bruce
  • 33,927
  • 76
  • 174
  • 262

1 Answers1

3

The specific type of an enumeration is implementation specific, but it is often an int. So yes, in this case s is probably an int. From the C spec:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until after the } that terminates the list of enumerator declarations.

So in your case, 4 will certainly work, since it fits in a char and in any signed or unsigned integer type on any machine I've ever heard of.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • How can I find the specific type. I am using gcc. – Bruce Feb 26 '12 at 06:28
  • 1
    Check the gcc documentation, I guess. You could use `sizeof` to get a baseline. – Carl Norum Feb 26 '12 at 06:32
  • 3
    I had another idea - you could deliberately make a `printf` format mismatch with your `s` variable - gcc will print a warning that includes the type name, I think. – Carl Norum Feb 26 '12 at 06:35
  • Nice! test.c:8: warning: format '%f' expects type 'double', but argument 2 has type 'unsigned int' – Bruce Feb 26 '12 at 06:40