Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon : used in variable initialization? [duplicate]

Tags:

c++

I found this line here:

uint32 bIsHungry : 1;

... and I've never seen this syntax used to initialize a variable.

I'm used to seeing this:

uint32 bIsHungry = 1;

It looks kind of like an initialization list, but for a single field?

What is it, what does it do, why should I care?

like image 560
Cody Smith Avatar asked Aug 06 '15 08:08

Cody Smith


2 Answers

That line is a bit field declaration and it declares a data member with an explicit bit-level size

Example from cppreference:

#include <iostream>
struct S {
 // three-bit unsigned field,
 // allowed values are 0...7
 unsigned int b : 3;
};
int main()
{
    S s = {7};
    ++s.b; // unsigned overflow
    std::cout << s.b << '\n'; // output: 0
}

Notice that in the example above the unsigned overflow is defined behavior (same doesn't apply if b were declared as a signed type)

The documentation you links also states that

Boolean types can be represented either with the C++ bool keyword or as a bitfield

Regarding why should I care I recommend reading this other question

like image 126
Marco A. Avatar answered Sep 29 '22 01:09

Marco A.


It is not initialization, it is a fragment of a declaration.

struct {
    // ...
    uint32 bIsHungry : 1;
    // ...
};

declares a bIsHungry as a bitfield member of the struct. It says that bIsHungry is an unsigned int whose length is 1 bit. Its possible values are 0 and 1.

Read more about bitfields: http://en.cppreference.com/w/c/language/bit_field

like image 25
axiac Avatar answered Sep 29 '22 00:09

axiac