------------------------------------------------------------------------------
MC logo
Boolean and Control
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Counted Average Example] [For Loop Average] [For Loops] [Read-To-End Average] [Reading In the While Test] [Counting Example 1] [Counting Example 2] [Counting Example 3] [Counting Example 4] [Counting Example 5] [Watch Out For This] [Switch] [Switch Using Break] [Break and Continue] [Change Adder]
Reading: Ch. 6 and 8 (except we are not covering strcmp just now)

C and C++ have the same control statements as Java: if, while, for, switch and do while, with break and continue if you want out early, or just can't seem to stop, respectively. Since these involve making decisions, they require a boolean type. Java has the basic type boolean for this purpose; couldn't be simpler. C++, however, has managed to make it not simple.

Plain C does not have a boolean type. Instead, it uses integer under the following general rules:

  1. An operation which requires a boolean value takes an integer and treats zero as false and any other value as true.
  2. An operation which produces a boolean value generates 1 or 0 for true and false.

C++ inherited this arrangement, but eventually added a boolean type to C++ (and called it bool, just to keep you from spelling right the first time). To maintain compatibility with C, bool converts freely to and from integer under similar rules. Specifically:

  1. When an integer is used in a boolean context, zero becomes false, and nonzero becomes true.
  2. When a bool is used in an int context, true becomes 1 and false becomes 0.

The bottom line is to produce the same behavior in either dialect, just using different type rules to get there.

Relational Operators

==       !=       <       <=       >       >=

C: Result is 1 or 0.

C++: Result is true or false.

Binary Logical Operators

&&       ||

In C: expect integer values, treating zero as false and non-zero as true. Produce 1 or 0.

In C++: expect boolean values. If integer(s) are present, convert to bool and produce true or false by the usual meaning of “and” and “or”.

Short circuit
if(n != 0 && sum / n > 1.0) ...

C and C++ logical operators use short-circuit evaluation, the same as Java.

Unary Logical Operator

The ! is the not operator. In plain C, it converts 0 to 1 and nonzero to 0. In C++, it returns the other boolean value. Of course, an integer argument is converted first.

Conditional Operator

expr_test ? expr_true : expr_false

When you want an if, but need an expression.

max = a < b ? b : a;

cout << "Max is " << a < b ? b : a << endl