I posted other question: http://stackoverflow.com/questions/3509470/what-type-should-i-use-for-binary-representation-of-c-enum, and by the answer, I have to know my compiler's enum data-type.
What's the data-type of C enum on Clang compiler?
I posted other question: http://stackoverflow.com/questions/3509470/what-type-should-i-use-for-binary-representation-of-c-enum, and by the answer, I have to know my compiler's enum data-type.
What's the data-type of C enum on Clang compiler?
Well, a compiler may chose an integer size big enough but I guess it will chose a "native" size (a "word" = size of register, should be long for x86 32bit mode or long long for x64). For your private struct you shouldn't care, but if you want to serialize it to a file or over the network then you should explicitly use an integer type that's big enough (e.g. long) so you can pick it up with another compiler/language without headaches.
If you really wanna know, just ask the compiler:
printf("%d\n", sizeof(enum myEnumType));
Like most (all, maybe) C compilers, the size of an enumerated type can vary. Here's an example program and its output:
#include <stdio.h>
typedef enum
{
val1 = 0x12
} type1;
typedef enum
{
val2 = 0x123456789
} type2;
int main(int argc, char **argv)
{
printf("1: %zu\n2: %zu\n", sizeof(type1), sizeof(type2));
return 0;
}
Output:
1: 4
2: 8
All that the standard requires is:
The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.
A quick web search didn't turn up a clang manual that specified its behaviour, but one is almost certainly out there somewhere.
In addition to Carl's answer it might even be compatible to a signed or unsigned type if anything of that fits better. E.g it could but mustn't in
enum small { m = -1; a = 127; };
enum big { b = 255; };
have small
in a signed char
and big
in an unsigned char
.
BTW the constants m
, a
and b
are not of enumeration type but always of type int
.
Edit: I just tested with values larger than int
. In C99 mode gcc
emits an error (which is correct) but clang
only issues a warning and than has a wider type to represent the enum
.