Ambiguity of if statements

Example:

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

Example:

if (temp > 25)
   if (temp < 50)
      cout << "It is normal." << endl ;
else 
   cout << "It is ?" << endl ;
What happens??


Because C++ pays no attention to layout (tabs, extra spaces), you need to know that C++ assumes that each else belongs to the nearest if that is not already matched with an else.

Thus in both examples above, the question mark should be replaced by warm.

To avoid such confusion, curly braces can be used. It is better programming practice to use braces to avoid potential misreading.

Example:

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


Using the not, !, operator

if (temp < 25)) 
   cout << "It is too cold!" << endl ;
and
if (!(temp >= 25)) 
   cout << "It is too cold!" << endl ;
are equivalent.