7E. Standards for If-Statements

The body of an if-statement must not be just semicolon

Do not write something like

  if(condition);
where the body is just a semicolon. Also, never write
  else;
If you want to say "do nothing", then use {}. To say "else do nothing", omit the else part.


Do not over-use if-statements by making unnecessary tests.

Here is an example.

  int maximum(int x, int y)
  {
    if(x == y)
    {
      return x;
    }
    else if(y > x)
    {
      return y;
    }
    else
    {
      return x;
    }
  }

The answer is either x or y. Notice that maximum returns x if either x == y or x > y. That suggests the following.

  int maximum(int x, int y)
  {
    if(x >= y)
    {
      return x;
    }
    else 
    {
      return y;
    }
  }

Do not write the same code at the beginning or end of both parts of an if-else statement.

For example, instead of

  if(condition)     
  {
    x = 1;
    ...
    return 0;
  }
  else
  {
    x = 1;
    ...
    return 0;
  }
write
  x = 1;
  if(condition)
  {
    ...
  }
  else
  {
    ...
  }
  return 0;


If one branch of an if-else statement does nothing, make it the else-branch, and omit else {}.

For example, instead of

  if(x > 0) 
  {
  }
  else 
  {
    doSomething();
  }
write
  if(x <= 0) 
  {
    doSomething();
  }


Do not use if-statements whose conditions must always be true or always be false.

For example, in

  if(x > 0)
  {
    step1();
  }
  else if(x <= 0)
  {
    step2();
  }
the second test, x <= 0, will always be true. So get rid of it.
  if(x > 0)
  {
    step1();
  }
  else
  {
    step2();
  }


If code is only done when one branch of an if-else statement is taken, then that code should be in that branch, not after the if-statement.

For example, look at the following.

  int demo(int x)
  {
    int y;
    if(x > 0)
    {
      y = x + 1;
    }
    else
    {
      return -x;
    }
    return y;
  }

Notice that line

  return y;
can only be done when x > 0. A more clear way to write it is

  int demo(int x)
  {
    int y;
    if(x > 0)
    {
      y = x + 1;
      return y;
    }
    else
    {
      return -x;
    }
  }

But remember that you should usually not store a value in a variable just so that you can return it. So an even better form is

  int demo(int x)
  {
    if(x > 0)
    {
      return x + 1;
    }
    else
    {
      return -x;
    }
  }

That makes it clear just what demo does.


See the standards for more details.


Exercises

  1. The coding standards forbid the following.

      if(n == 0){}
      else
      {
        z = 1;
      }
    
    Rewrite that into an acceptable form that does the same thing. Answer

  2. The coding standards disallow the following. Explain what is going on and how to avoid this.

      if(x == 0)
      {
        y = 1;
      }
      else if(x != 0)
      {
        y = 2;
      }
    
    Answer