1

Related to this and this.

If I define

bool y = true;
bool n = false;

is the bit-wise content of the 1-byte storage of y and n mandated by the standard? If so, which are those two contents? If not, then how is the comparison between bools themselves or between bools and other integer types handled?

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • https://en.cppreference.com/w/cpp/language/types, the size of bool is implementation defined and may not be equal to one. So there is nothing in the standard that says a boolean must be one bit. (not even in bitfields, just that a boolean and its representation in a bitfield must compare equal). And then the standard has a lot to say about conversions to bool (e.g. from int) – Pepijn Kramer Feb 13 '23 at 12:50
  • 1
    The standard doesn't define how compilers handle things internally. `true` has to be equal to all other `true` values, just like `0.0` has to be equal to `0.0` (even on systems which have signed zero, and therefore two bit patterns that both represent zero). – MSalters Feb 13 '23 at 13:04

1 Answers1

3

Standard does not require any bit representation for bool, it only requires that there are two values true and false - and in particular, it doesn't seem to require that there is only one representation for each value ([basic.fundamental]#10):

Type bool is a distinct type that has the same object representation, value representation, and alignment requirements as an implementation-defined unsigned integer type.
The values of type bool are true and false.

It is required that true is mapped to 1 and false is mapped to 0 when converting bool to int ([conv.prom]#6):

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 1
    "Same value representation" sounds a bit weird in context. There's no unsigned integer type with values `true` or `false`, so how can `bool` have the same value representation? – MSalters Feb 13 '23 at 13:01
  • @MSalters I can't say I understand it fully, but the same is used to refer to unsigned vs signed types and they only have partly overlapping set of values. It seems that if the unsigned type would have values `true` and `false` for some reason, they would be the same, but since the value sets are non-overlapping, this part doesn't apply. – Yksisarvinen Feb 13 '23 at 13:12
  • @MSalters https://timsong-cpp.github.io/cppwp/n4868/basic.types.general#def:representation,value – Language Lawyer Feb 13 '23 at 13:16
  • @LanguageLawyer: Tricky that. It means that `bool` has the same number of value and padding bits as that other type, so it can't be 1+7. – MSalters Feb 13 '23 at 13:22
  • 1
    @MSalters When we talk about *value representation*, then we are not talking about *values*, but about the bit patterns that represent the values. Hence, there is no weirdness. – j6t Feb 13 '23 at 13:43