Search code examples
cstandardsarithmetic-expressionsinteger-arithmetic

What can bool type return in C99?


What is bool guaranteed to return as? Can I rely on a bool type to always be interpreted as 0 or 1? If bool's numerical interpretation isn't reliable in C99 is there a standard where it is? Are there any things I should look out for in LLVM, GCC, or Visual C++ when relying on bool for arithmetic?

Just for example what if I did this:

// An example of calculating a possible stride in bytes.
// hasData(), is8bit(), and is16bit() return as bool type

unsigned int stride = object->hasData() * object->size() * 
                      (object->is8bit()  * sizeof(uint8_t) + 
                       object->is16bit() * sizeof(uint16_t));

In the example I'm betting on bool type only returning 0 or 1.


Solution

  • The C99 standard requires the compiler to produce _Bool values that are either 0 or 1. C++ also has this requirement. No, I don't know the exact page of the standard document that describes this.

    Of course, 16 years after the introduction, it's still possible that there are bugs in compilers, and more so if we have a compiler that is, say, 10 years old and wasn't well tested for C99 compatibility when it was produced. But I frequently write code that relies on the compiler producing 0 or 1 from conditional expressions, for example.