Control Constructs

C++ provides several control constructs, mostly familiar from Java. The for, while and switch are old friends, with a for-each version added with the 2011 standard.

For control statements, you need boolean expressions. These look a lot like Java's, and cover mostly the same operators. But there are some interesting semantic differences we'll look at as we go. And the type name is bool, just to make sure you're paying attention.

The comparison operators are what you are used to: ==, !=, <, <=, > and >=. One minor difference is that they work properly on strings. No need to call an equals or compareTo method.

The logical operations are also the same, &&, || and !. Also like Java, the operators are short-circuit, meaning that evaluation stops when the answer is known. This is important for expressions like n > 0 && t / n > 1, where the short-circuit evaluation prevents division by zero. It is also very useful to check subscripts before using them (see the array section).

Textbook: Chapters 3 and 4. Note that the book does not discuss the for-each form of the for loop.

[more info]