C++ – Why Boolean Type Supports ++ but Not —

booleanchistoryoperators

Why does the operator -- not exist for bool whereas it does for operator ++?

I tried in C++, and I do not know if my question apply to another language. I will be glad to know also.

I know, I can use the operator ++ with a bool. It makes any bool equal to true.

bool b = false;
b++;
// Now b == true.

Why can't we use the operator -- in an opposite way?

bool b = true;
b--;
// Now b == false;

It is not very useful, but I am curious.

Best Answer

In the old days of C, there was no boolean type. People used the int for storing boolean data, and it worked mostly. Zero was false and everything else was true.

This meant if you took an int flag = 0; and later did flag++ the value would be true. This would work no matter what the value of flag was (unless you did it a lot, it rolled over and you got back to zero, but lets ignore that) - incrementing the flag when its value was 1 would give 2, which was still true.

Some people used this for unconditionally setting a boolean value to true. I'm not sure it ever became idiomatic, but its in some code.

This never worked for --, because if the value was anything other than 1 (which it could be), the value would still not be false. And if it was already false (0) and you did a decrement operator on it, it wouldn't remain false.

When moving code from C to C++ in the early days, it was very important that C code included in C++ was still able to work. And so in the specification for C++ (section 5.2.6 (its on page 71)) it reads:

The value obtained by applying a postfix ++ is the value that the operand had before applying the operator. [Note: the value obtained is a copy of the original value ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a complete object type. After the result is noted, the value of the object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. [Note: this use is deprecated, see annex D. ]

The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool.

This is again mentioned in section 5.3.2 (for the prefix operator - 5.2.6 was on postfix)

As you can see, this is deprecated (Annex D in the document, page 709) and shouldn't be used.

But thats why. And sometimes you may see the code. But don't do it.