A syntax note: if the code that follows the conditional expression consists of only one statement, then the curly braces are optional. So the following code is equivalent to the previous example.
BOOL isNotLegal = !((truckWeight > 0.0) && (truckWeight < 40000.0)); if (isNotLegal) printf("Truck weight is not within legal range.n");
However, the curly braces are necessary if the code consists of more than one statement.
BOOL isNotLegal = !((truckWeight > 0.0) && (truckWeight < 40000.0)); if (isNotLegal) { printf("Truck weight is not within legal range.n"); printf("Impound truck.n"); }
Why? Imagine if you removed the curly braces.
BOOL isNotLegal = !((truckWeight > 0.0) && (truckWeight < 40000.0)); if (isNotLegal) printf("Truck weight is not within legal range.n"); printf("Impound truck.n");
This code would make you very unpopular with truck drivers. In this case, every truck gets impounded regardless of weight. When the compiler does not find a curly brace after the conditional, only the next statement is considered part of the if construct. Thus, the second statement is always executed. (What about the indention of the second statement? While indention is very helpful for human readers of code, it means nothing to the compiler.)
In this book, we will always include the curly braces.