Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...