9C. Pitfalls with If-Statements

Watch out: equality tests

If you are doing an equality test, be sure to use ==, not =. Statement
  if(n = 0)
  {
     m = 1;
  }
  else 
  {
     m = 2;
  }
always makes m = 2. Expression n = 0 is not a test, it is an assignment. It stores 0 into n, and yields result 0. Since 0 is treated as false, the else-part is performed.

If you ask g++ to give common warnings (option -Wall), it will let you know about this mistake, with a message similar to the following.

test.cpp:7:11: warning: suggest parentheses around assignment
used as truth value [-Wparentheses]
   if(n = 0)
           ^

Do not use = in a test even if it is what you want. The coding standards do not allow that.


Watch out: semicolons

Be careful about semicolons. A lone semicolon is a statement that does nothing. Statement
  if(n == 0);
  {
    printf("n is zero\n");
  }  
always writes "n is zero", regardless of the value of n. The semicolon at the end of the first line is an empty statement, so the if-statement says, if n equals 0, do nothing. The statement after that is just a compound statement. This really does two statements in a row.

The coding standards require you not to use a semicolon as an empty statement, and explicitly forbid using a semicolon as the body of an if-statement.