In C++, the stream I/O libraries do not by default print "true" or "false" when you output a bool, but rather "1" or "0". Instead, one is required to explicitly request a word-based printing, via std::boolalpha/std::noboolalpha:
#include <iostream>
int main()
{
std::cout << bool{ false }; //Prints "0"
std::cout << std::boolalpha; //Print all bools with alphanumerics
std::cout << bool{ false }; //Prints "false"
std::cout << std::noboolalpha; //Return to default
}
Leaving aside whether this is appropriate as a default (it's definitely confusing for beginners), I'm not sure why C++ offers the bool-as-numeric functionality at all. Some plausible reasons I can think of:
- The mess of standardizing
boolbetween C89, C99, and C++, might have meant that an overload foroperator<<could not distinguish betweenbools andints, - Primitive localization support ("true" in English is not the same as "Wahr" in German, but "1" is "1" everywhere...that uses Arabic numerals), or just
- The "output parameter" problem when serializing to disk (
std::ofstream{"filename"} << static_cast<int>(my_bool_variable);isn't particularly onerous, but the input analogue requires a temporary variable.)
In any case, I can't find the actual (historical) reason on the web; for example, the topic is never address in the C++FAQ, for example. So: Why does C++ offer this bool-as-numeric functionality in its input/output streams?