fyasir
fyasir

Reputation: 2970

How can I define a datatype with 1 bit size in C?

I want to define a datatype for boolean true/false value in C. Is there any way to define a datatype with 1 bit size to declare for boolean?

Upvotes: 1

Views: 7892

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

Maybe you are looking for a bit-field:

struct bitfield
{
     unsigned b0:1;
     unsigned b1:1;
     unsigned b2:1;
     unsigned b3:1;
     unsigned b4:1;
     unsigned b5:1;
     unsigned b6:1;
     unsigned b7:1;
};

There are so many implementation-defined features to bit-fields that it is almost unbelievable, but each of the elements of the struct bitfield occupies a single bit. However, the size of the structure may be 4 bytes even though you only use 8 bits (1 byte) of it for the 8 bit-fields.

There is no other way to create a single bit of storage. Otherwise, C provides bytes as the smallest addressable unit, and a byte must have at least 8 bits (historically, there were machines with 9-bit or 10-bit bytes, but most machines these days provide 8-bit bytes only — unless perhaps you're on a DSP where the smallest addressable unit may be a 16-bit quantity).

Upvotes: 4

david.pfx
david.pfx

Reputation: 10868

The answer is _Bool or bool.

C99 and later have a built-in type _Bool which is guaranteed to be large enough to store the values 0 and 1. It may be 1 bit or larger, and it is an integer.

They also have a library include which provides a macro bool which expands to _Bool, and macros true and false that expand to 1 and 0 respectively.

If you are using an older compiler, you will have to fake it.

[edit: thanks Jonathan]

Upvotes: 1

Raging Bull
Raging Bull

Reputation: 18737

Try this:

#define bool int
#define true 1
#define false 0

In my opinion use a variable of type int. That is what we do in C. For example:

int flag=0;
if(flag)
{
    //do something
}
else
{
    //do something else
}

EDIT:

You can specify the size of the fields in a structure of bits fields in bits. However the compiler will round the type to at the minimum the nearest byte so you save nothing and the fields are not addressable and the order that bits in a bit field are stored is implementation defined. Eg:

struct A {
  int a : 1; // 1 bit wide
  int b : 1;
  int c : 2; // 2 bits
  int d : 4; // 4 bits
};

Bit-fields are only allowed inside structures. And other than bit-fields, no object is allowed to be smaller than sizeof(char).

Upvotes: 1

Related Questions