Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef a bitfield variable

I want to have a typedef that is 1-bit integer, so I though of this typedef int:1 FLAG; but I'm getting errors with it, is there a way I can do so? Thanks

like image 231
hakuna matata Avatar asked Oct 23 '25 14:10

hakuna matata


1 Answers

No.

The smallest addressable "thing" in a C Program is a byte or char.
A char is at least 8 bits long.
So you cannot have a type (or objects of any type) with less than 8 bits.

What you can do is have a type for which objects occupy at least as many bits as a char and ignore most of the bits

#include <limits.h>
#include <stdio.h>

struct OneBit {
    unsigned int value:1;
};
typedef struct OneBit onebit;

int main(void) {
    onebit x;
    x.value = 1;
    x.value++;
    printf("1 incremented is %u\n", x.value);
    printf("each object of type 'onebit' needs %d bytes (%d bits)\n",
          (int)sizeof x, CHAR_BIT * (int)sizeof x);
    return 0;
}

You can see the code above running at ideone.

like image 98
pmg Avatar answered Oct 25 '25 04:10

pmg