Skip to content
Topos Uranos

Summary

A condition is an expression whose value is true or false. This lesson studies how conditions are built in C++: the six relational operators, which compare two values and produce a bool; the three logical connectives, &&, || and !, which combine conditions like the conjunction, the disjunction and the negation of logic; and the precedence that orders them among themselves and with respect to arithmetic. It also studies two features in which C++ departs from mathematical writing: the chain 1 < x < 5, which compiles and does not mean what it seems, and short-circuit evaluation, by which the second operand of && and of || is not evaluated when the first already decides the result, which makes it possible to protect a dangerous operation. It ends with the negation of compound conditions by means of De Morgan’s laws, checked with truth tables, and with its central example: the leap year condition and its negation. The unit has no decisions yet: conditions are evaluated and printed as true or false, and the lesson Decisions will put them in charge of the program.

Learning objectives

  1. Write in C++ compound conditions that translate statements such as “xx is between 1 and 10, endpoints included”.
  2. Negate a compound condition with De Morgan’s laws and check the equivalence with a truth table.
  3. Use short-circuit evaluation to protect an operation, as in count != 0 && total / count > 2.
  4. Detect the error of writing 1 < x < 5, explain what it computes and correct it.

The condition as an expression

The lesson Characters, Booleans, conversions and constants introduced the type bool, with its two values true and false, and the lesson Arithmetic showed that an expression has a tree, fixed by precedence and associativity, and a type, fixed by its operands. This lesson brings both ideas together. A condition is an expression of type bool: not a statement that asks something, but a computation whose result is an answer. count < 10 is computed as count + 1 is: the operands are taken, the operator is applied and a value is obtained, except that the value is true or false instead of a number. If this is so, everything that holds for arithmetic expressions holds for conditions: they have precedence, they have a tree, they can be stored in a named variable (const bool inRange{…}) and they can be printed. From this follows the question that runs through the lesson: given a sentence (“the year is a leap year”, “the age is between 18 and 65”), which expression has exactly that truth value for every possible datum?