Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 810
Rüppell's Vulture Avatar asked Oct 04 '22 05:10

Rüppell's Vulture


1 Answers

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.

like image 134
Pascal Cuoq Avatar answered Oct 13 '22 00:10

Pascal Cuoq