9 bool, 0 and non-zero

C and C++ treat boolean types differently. In my opinion, it is not different enough.

In C, there is no built-in bool type. You can use any scalar type (char, short, unsigned, etc., even float!) to represent a boolean value. The value 0 (zero) means false, and any non-zero value means true.

This convention started with the root of assembly language programming. There is no boolean type in assembly language. However, it is common to use the Z (zero) flag of an ALU (arithmetic and logic unit) to indicate true or false. Though handy, this ``feature'' of C often leads to disaster.

Let's consider the following code:

int x, y;
// ...  
if (x == y)
{
  cout << "same" << endl;
}
else
{
  cout << "different" << endl;
}

This is fine. The result of a comparison should be of boolean type. Furthermore, the condition of an if-else statement should expect a boolean expression. What if there is a typo, and the code becomes the following?

if (x = y) // one equal!

gcc, by default, does not generate a warning. If you turn on the warnings, it'll say ``suggest parentheses around assignment used as truth value''. What is the value of x = y? It is the value of y! As a result, the behavior of the code changes in subtle ways. Note that the value of x also gets changed in the incorrect code, leading to more problems down the line.

This happens because of two reasons. First, C treats assignment as an operator, not a statement. Therefore, it is possible to specify an assignment in a condition. Second, C has no boolean type, so any scalar expression is okay in a condition.

C++ does have a built-in bool type. It also has built-in constants true and false. However, without enforcing that logical operators must have bool types on both sides, and that conditions must be bool expressions, the introduction of the bool type has limited use.

Copyright © 2006-08-29 by Tak Auyeung