What's the data-type of C enum of Clang compiler?
Asked Answered
E

3

7

I posted other question: 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?

Edify answered 18/8, 2010 at 6:42 Comment(0)
S
10

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.

Stringhalt answered 18/8, 2010 at 6:56 Comment(1)
clang-11 is putting my 64-bit enum values into a 32-bit type. They get truncated. So apparently not all mainstream compilers follow the spec. :-/Gamble
F
2

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.

Fifty answered 18/8, 2010 at 7:4 Comment(0)
H
1

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));
Hansel answered 18/8, 2010 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.