Although you can rely on the rule that if-false statements belong
to the nearest unmatched if
statement, it is better programming
practice to use braces to avoid potential misreading.
In the following example, it is clear that the question mark should be
replaced by warm
, for the braces clearly group the if-false
statement with the second if
statement.
if (temperature > 25) { if (temperature < 50) cout << "It is normal." << endl; else cout << "It is too ?." << endl; }
On the other hand, in the following example, it is clear
that the question mark should be replaced by cold
, for
this time the braces clearly group the if-false
statement with the first if
statement.
if (temperature > 25) { if (temperature < 50) cout << "It is normal." << endl; } else cout << "It is too ?." << endl;