Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
eonil Avatar asked Oct 21 '10 02:10

eonil


People also ask

Why do we use colons in C?

It's commonly used to pack lots of values into an integral type. In your particular case, it defining the structure of a 32-bit microcode instruction for a (possibly) hypothetical CPU (if you add up all the bit-field lengths, they sum to 32).

What does colon in C mean?

They can be used as "dummy" fields, for alignment purposes. An unnamed bit field whose width is specified as 0 guarantees that storage for the member following it in the struct-declaration-list begins on an int boundary. This example defines a two-dimensional array of structures named screen.

What does colon mean in constructor?

It's called an initialization list. It initializes members before the body of the constructor executes.


2 Answers

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.

like image 197
EboMike Avatar answered Oct 07 '22 09:10

EboMike


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.

like image 32
R.. GitHub STOP HELPING ICE Avatar answered Oct 07 '22 10:10

R.. GitHub STOP HELPING ICE