The Truth About Boolean

The boolean type in C++ is written bool. (This is one of the features carefully designed to keep Java programmers off balance.) Unlike Java and most languages, C++ boolean type freely convertable to and from integer. (We'll discuss C++ rather than plain C, which doesn't even have a boolean type. But overall effect there is similar.)

The Rules

  1. When a boolean is converted to an integer, true converts to 1 and false converts to 0.
  2. When an integer is converted to a boolean, zero converts to false, and all other values (including negative ones) convert to true

In addtion, many of the I/O operations return boolean values, or types which automatically convert to boolean.

Why It Matters

The automatic conversion rules allow you to use numeric expressions as tests in if's, while's and for's. This allows some convenient things, and some crazy things.

Since I/O operations return boolean, they can be used as tests. This allows I/O operations to be performed in loop tests so that the loop is controlled by the success of the I/O operation.