Within the US, we charge $5, but for the State of Hawaii (which is very remote), we charge $10.
Outside the US, we charge $20.
The following is an if-statement that is used to compute the "shippingCharge":
Example: an ambiguious program (can be read in more than one way...)
double shippingCharge; shippingCharge = 5.00; // Charge is at least $5 if ( country is equal to "USA") ) if ( state is equal to "HI" ) shippingCharge = 10.00; // Hawaii is $10 else shippingCharge = 20.00; // Outside USA is $20 |
One solution (used in the programming language Modula) is to close the IF-statement with a new key-word:
if ( boolean expression ) one-or-more-statement fi |
double shippingCharge; shippingCharge = 5.00; // Charge is at least $5 if ( country is equal to "USA") ) if ( state is equal to "HI" ) shippingCharge = 10.00; // Hawaii is $10 fi else shippingCharge = 20.00; // Outside USA is $20 fi |
There is ONLY ONE WAY to read this program segment (try it !)
So, the C/C++ compiler will read this program as:
double shippingCharge; shippingCharge = 5.00; if ( country.equals("USA") ) if ( state.equals("HI") ) shippingCharge = 10.00; else shippingCharge = 20.00; |
So, the proper way to write the program is:
double shippingCharge; shippingCharge = 5.00; if ( country.equals("USA") ) { if ( state.equals("HI") ) shippingCharge = 10.00; // Shipping to Hawaii is $10 } else shippingCharge = 20.00; // Shipping to outside USA is $20 |
Associating the else with the second if will cause a syntax error !!!