| Another Average Example |
The C language does not have a boolean type. Instead, it uses integer under the following general rules:
The C++ committee 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, it converts freely to and from integer under similar rules. Specifically:
Relational Operators
==
!=
<
<=
>
>=
C: Result is 1 or 0.
C++: Result is true or false.
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 using the rule that zero converts to false, nonzero converts to true. Produce true or false.
Short circuit
if(n != 0 && sum / n > 1.0) ...
Conditional Operator
expr_test ? expr_true : expr_false
When you want an if, but need an expression.
max = a < b ? b : a;
printf("Max is ", a < b ? b : a);
| Another Average Example |