Can bit-fields only be fields of a structure/union, never "normal", "stand-alone" variables?

StackOverflow https://stackoverflow.com/questions/16373465

  •  14-04-2022
  •  | 
  •  

Question

The field part of bit-fields seems to suggest that they can only be fields inside a structure or union.

Can a bit-field be a typical "stand-alone" variable, outside any aggregate data-type like union or structure as follows:

   int sum:6;   //Can this work as a declaration statement?
   sum=4;

If not, why so? If bit-fields are basically intended to use less memory, why can't we declare any variable as a bit-field if we know it won't exceed that size?

Was it helpful?

Solution

Bit-fields are only part of structs or unions because that's what the C standard allows. It would have been possible to decide differently. Why the committee decided to write the standard the way it is, you would have to ask them.

To find the information in the C99 standard:

From the table of contents:

6.7 Declarations

6.7.2 Type specifiers (okay, this one is a little bit obscure)

6.7.2.1 Structure and union specifiers.

One bit-field is the declarator_opt : constant-expression part of the syntax. This syntax is only allowed here, and a consequence is that one cannot declare bit-fields elsewhere.

The syntax tells you that the name of a bit-field can optionally be omitted, if you were curious for this sort of information. Clause 6.7.2.1:3 goes further and prohibits names for 0-length bit-fields.

OTHER TIPS

Bit fields can only be defined in structs and unions where they can be referred to individually by name. You cannot address memory by bits, a minimum of a byte size is required (8 bits). In order to address a variable bit by bit, you may use a mask like so:

int num = 9;
int fourthBit = (num >> 4) & 1;

A struct can have a bigger size, for example an int (of 4 bytes) and then be divided, by bits, to different pieces. Of course, the assignment will be compiled using masks.

Refer to this for more info: http://msdn.microsoft.com/en-us/library/yszfawxh(v=vs.80).aspx

If not, why so? If bit-fields are basically intended to use less memory, why can't we >declare any variable as a bit-field if we know it won't exceed that size?

Because the memory is fixed at 16 or 32 bits wide. It would be too slow to pack a users 14 bit ints into 16 bits and use the other 2 bits . Its better to waste the 2 bits and don't let you define in efficient storage. Thats why if you really want to you can use a union. You wouldn't be gaining anything by making the compiler work harder for nothing. The people who wrote the compiler were smart. They don't just let a programmer with a bad idea slow things down, sorry/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top