Benjy Kessler
Benjy Kessler

Reputation: 7656

Converting bool to bit in bitfield

I have a bitfield:

struct MyBitfield {
  unsigned char field1: 1;
  unsigned char field2: 1;
};

These bitfield arguments are 1 bit wide and represent boolean values. I was wondering if it is valid to initialize it with bools as follows

MyBitfield my_bitfield = {true, false};

My question is whether this behavior is well defined. IIUC, false always evaluates to 0 but true can evaluate to any non-zero integer. If it happens to evaluate to an integer whose LSB is 0, will it be cast to the bit 0 and evaluate to false or does the language guarantee that it will always be cast to the bit 1?

Upvotes: 1

Views: 2525

Answers (3)

user1810087
user1810087

Reputation: 5334

From the current draft n4750:

§12.2.4/3

[...] A bool value can successfully be stored in a bit-field of any nonzero size. [...]

Also valid for C++03 §9.6/3.

Upvotes: 0

Dorian Turba
Dorian Turba

Reputation: 3765

Short answer : Yes, the language guarantee that it will always be cast to the bit 1.

Long answer :

There is some good information here : Can I assume (bool)true == (int)1 for any C++ compiler?

If the source type is bool, the value false is converted to zero and the value true is converted to one.

http://en.cppreference.com/w/cpp/language/bool_literal :

#include <iostream>

int main()
{
  std::cout << std::boolalpha
            << true << '\n'
            << false << '\n'
            << std::noboolalpha
            << true << '\n'
            << false << '\n';
}

Output:

true
false
1
0

So yes, the language guarantee that it will always be cast to the bit 1.

Upvotes: 1

super
super

Reputation: 12978

On cppreference we can read:

If the source type is bool, the value false is converted to zero and the value true is converted to the value one of the destination type (note that if the destination type is int, this is an integer promotion, not an integer conversion).

Your code is ok.

Upvotes: 1

Related Questions