Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about class definition in C++ " : 1" [duplicate]

Tags:

c++

clang

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!

like image 784
Lei Mou Avatar asked Jun 10 '11 13:06

Lei Mou


2 Answers

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.

like image 127
Macke Avatar answered Nov 15 '22 15:11

Macke


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.

like image 36
Alexey Malistov Avatar answered Nov 15 '22 15:11

Alexey Malistov