Question

It was my understanding that the type for the bit field declarator should be of some int type. In fact, here is the line from the C99 standard

"A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed >int, unsigned int, or some other implementation-defined type."

However, I came across some code today which shows an enum as the type, like this.

typedef enum
{
    a = 0,
    b = 1
}ENUM;

typedef struct
{
    ENUM id : 8;
}STRUCT;

Without comments or documentation, it's hard to tell the intent. Could anyone provide some insight?

Was it helpful?

Solution

a and b are both of the int type, signed int. It has a length of 32 bit, meaning 4 Byte.

But the enum ENUM does not need that much.

0000000000000000000000000000000 equals a
0000000000000000000000000000001 equals b

So the creator thought making the ENUM shorter than int with a bitfield of the length of 8 bit, minimum length 1 Byte.

00000000 or 00000001

He could have taken the char type from the beginning with the length of 1 Byte though.

On some compilers you can activate a feature to ensure an enum can be smaller than int. Using the option --short-enums of GCC, makes it use the smallest type still fitting all the values.


Here is an example how you would save memory with a bitfield. You see the someBits struct is smaller than twoInts struct.

#include "stdio.h"

struct oneInt {
  int x;
};

struct twoInts {
  int x;
  int y;
};

struct someBits {
  int x:2; // 2 Bits
  int y:6; // 6 Bits
};


int main (int argc, char** argv) {
  printf("type int = %lu Bytes\n", sizeof(int));
  printf("oneInt = %lu Bytes\n", sizeof(struct oneInt));
  printf("twoInts = %lu Bytes\n", sizeof(struct twoInts));
  printf("someBits = %lu Bytes\n", sizeof(struct someBits));
  return 0;
}

Output:

type int = 4 Bytes
oneInt = 4 Bytes
twoInts = 8 Bytes
someBits = 4 Bytes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top