Colons after variable name in C [duplicate]
Possible Duplicate:
What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?
This is C code sample of a reference page.
signed int _exponent:8;
What's the meaning of the colon before '8' and '8' itself?
It's a bitfield. It's only valid in a struct
definition, and it means that the system will only use 8 bits for your integer.
It's a bitfield, an obscure and misguided feature of structures. That should be enough for you to lookup the information you need to know to deal with bitfields in other people's code. As for your own code, never use bitfields.
Edit: As requesed by Zack, bitfields have significant disadvantages versus performing your own bit arithmetic, and no advantages. Here are some of them:
- You can only copy, compare, serialize, or deserialize one bitfield element at a time. Doing your own bit arithmetic, you can operate on whole words at a time.
- You can never have a pointer to bitfield elements. With your own bit arithmetic, you can have a pointer to the larger word and a bit index within the word as a "pointer".
- Directly reading/writing C structures to disk or network is half-way portable without bitfields, as long as you use fixed-size types and know the endianness. Throw in bitfields, though, and the order of elements within the larger type, as well as the total space used and alignment, become highly implementation-dependent, even within a given cpu architecture.
- The C specification has very strange rules than allow the signedness of bitfield elements to be different from what you'd expect it to, and very few people are aware of these.
For single-bit flags, using your own bit arithmetic instead of bitfields is a complete no-brainer. For larger values you need to pack, if it's too painful to write out all the bit arithmetic all over the place, write some simple macros.
It is a bitfield specification.
It means _exponent
takes only 8
bits out of the signed int
which typically takes more than 8
bits. Typically, bit-fields are used with unsigned types.
IIRC, compiler would warn if a something that does not fit into 8-bits is written into _exponent
.
When that statement is inside a structure, means bit fields.
精彩评论