C enum as a type in a structure when using bit fields -
it understanding type bit field declarator should of int type. in fact, here line c99 standard
"a bit-field shall have type qualified or unqualified version of _bool, signed >int, unsigned int, or other implementation-defined type."
however, came across code today shows enum type, this.
typedef enum { = 0, b = 1 }enum; typedef struct { enum id : 8; }struct;
without comments or documentation, it's hard tell intent. provide insight?
a
, b
both of int
type, signed int
. has length of 32 bit, meaning 4 byte.
but enum enum
not need much.
0000000000000000000000000000000 equals 0000000000000000000000000000001 equals b
so creator thought making enum
shorter int
bitfield
of length of 8 bit, minimum length 1 byte.
00000000 or 00000001
he have taken char
type beginning length of 1 byte though.
on compilers can activate feature ensure enum can smaller int. using option --short-enums of gcc, makes use smallest type still fitting values.
here example how save memory bitfield. see somebits
struct smaller 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
Comments
Post a Comment