// Mr. Minich
// CMPSC 201
// Ch. 4 Demo Program #4
// January 30, 2000
// Purpose - to illustrate common errors related to the use of the C++ if statement
#include <iostream.h>
int main()
{
int num1 = -5; // used in if statement examples
int num2 = 0; // used in if statement examples
if (num1)
{
cout << "This prints if num1 is nonzero.\n";
}
// I recommend the use of curly braces in the statement above even though
// they are technically optional in this situation.
if (num1 && num2)
{
cout << "This prints if num1 AND num2 are both nonzero.\n";
cout << "This also prints if num1 AND num2 are both nonzero.\n";
}
// Here the curly braces are required since 2 or more statements are included in the
// the conclusion of the if statement.
if (num1)
cout << "This prints if num1 is nonzero.\n" << endl;
if (num1 && num2)
cout << "This prints if num1 AND num2 are both nonzero.\n";
cout << "This prints ALSO if num1 AND num2 are both nonzero.\n";
// This if statement has incorrect logic (and incorrect indentation). Since the programmer did not
// use curly braces to surround the conclusion cout statements. The fact
// that the second cout statement is indented does not cause it to be
// interpreted as part of the if statement. It turns out that the message
// This prints ALSO if num1 AND num2 are both nonzero
// always prints out no matter what the result of the control expression
// (num1 && num2) may be.
if (num1 == 0);
cout << "This always prints out due to another logic error.\n";
// Because of the semicolon after the control expression, the cout
// statement is not treated as part of the if statement and is always
// executed no matter what the result of (num1 == 0) may be. It is a
// common error to incorrectly place semicolons after control expressions
// in if statements.
return 0;
}// end of main