Is it possible to create a data type of length one bit in C

Contrary to what some people believe, there is a data type of one bit in C99: it's called _Bool. You can also declare bitfields of size 1. The fact that individual bits are not addressable in C does not mean that one-bit data types cannot exist. That argument is basically comparing apples to oranges.

There isn't, however, a type of which the storage size (sizeof) is less than one byte.


It is not really possible to create a type that occupies one bit. The smallest addressable unit in C is the char (which is by definition one byte and usually, but not necessarily, 8 bits long; it might be longer but isn't allowed to be shorter than 8 bits in Standard C).

You can approach it with :

typedef _Bool uint1_t;

or:

#include <stdbool.h>
typedef bool uint1_t;

but it will occupy (at least) one byte, even though a Boolean variable only stores the values 0 or 1, false or true.

You could, in principle, use a bit-field:

typedef struct
{
    unsigned int x : 1;
} uint1_t;

but that will also occupy at least one byte (and possibly as many bytes as an unsigned int; that's usually 4 bytes) and you'll need to use .x to access the value. The use of bit-fields is problematic (most aspects of them are implementation defined, such as how much space the storage unit that holds it will occupy) — don't use a bit-field.

Including amendments suggested by Drew McGowen, Drax and Fiddling Bits.

Tags:

C