Home Segments Index Top Previous Next

281: Mainline

Note the ambiguity in the following nested if statement:

if (temperature > 25) 
   if (temperature < 50) 
     cout << "It is normal." << endl; 
     else cout << "It is too ?." << endl; 

With what should you replace the question mark: warm or cold? As laid out on the page, it seems that warm is the right answer. Laid out another way, however, you might have the impression that cold is the right answer:

if (temperature > 25) 
   if (temperature < 50) 
     cout << "It is normal." << endl; 
   else cout << "It is too ?." << endl; 

Because C++ pays no attention to layout, you need to know that C++ assumes that each else belongs to the nearest if that is not already matched with an else. Thus, the question mark should be replaced by warm.