Does the C++ specification define:
- the existence of the 'less than' operator for boolean parameters, and if so,
- the result of the 4 parameter permutations?
In other words, are the results from the following operations defined by the specification?
false < false
false < true
true < false
true < true
On my setup (Centos 7, gcc 4.8.2) , the code below spits out what I'd expect (given C's history of representing false as 0 and true as 1):
false < false = false
false < true = true
true < false = false
true < true = false
Whilst I'm pretty sure most (all?) compilers will give the same output, is this legislated by the C++ specification? Or is an obfuscating, but specification-compliant compiler allowed to decide that true is less than false?
#include <iostream>
const char * s(bool a)
{
return (a ? "true" : "false");
}
void test(bool a, bool b)
{
std::cout << s(a) << " < " << s(b) << " = " << s(a < b) << std::endl;
}
int main(int argc, char* argv[])
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
}
Best Answer
TL;DR:
The operations are well defined according to the draft C++ standard.
Details
We can see that by going to the draft C++ standard section
5.9
Relational operators which says (emphasis mine going forward):and bools are arithematic types from 3.9.1 Fundamental types
and
and
true
andfalse
are boolean literals from2.14.6
Boolean literals:Going back to section
5.9
to see the mechanics of the relational operators further, it says:the usual arithmetic conversions are covered in section
5
which says:and section
4.5
says:and so the expressions:
using these rules become: