Possible Duplicate:
What does 'unsigned temp:3' means
I encountered a problem when I'm reading the code of Clang.
class LangOptions {
public:
unsigned Trigraphs : 1; // Trigraphs in source files.
unsigned BCPLComment : 1; // BCPL-style '//' comments.
...
};
This is the first time I saw the syntax " : 1", what's the " : 1" stands for? Thanks!
It's a bitfield, which means that the value will only use one bit, instead of 32 (or whatever sizeof(unsigned) * <bits-per-byte>
is on your platform).
Bitfields are useful for writing compact binary data structures, although they come with some performance cost as the compiler/CPU cannot update a single bit, but needs to perform AND/OR operations when reading/writing a full byte.
Trigraphs
and BCPLComment
use 1 bit only for saving values.
For example,
struct S
{
signed char type : 2;
signed char num : 4;
signed char temp : 2;
};
uses only 8 bit of memory. struct S
may use a single byte or memory.
sizeof(S)
is 1 for the case of some implementations.
But type
and temp
is equal to 0,1,2 or 3. And num
is
equal 0,1,2,..., 15 only.
These are bit fields. The "1" is the width in bits.
See the C FAQ for an explanation.
精彩评论