|
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.
Look at the following. if(x > 0) { step1(); } else if(x <= 0) { step2(); }In 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. |
If a value is only used in one branch of an if-statement, it should be computed in that branch.
For example, instead of
int r = findLargest(n); if(n == 1) { return 1; } else { return max(r, findBig(n-1)); }write if(n == 1) { return 1; } else { int r = findLargest(n); return max(r, findBig(n-1)); }where findLargest(n) is only computed in the branch that uses it. |
See the standards for more details.
The coding standards forbid the following.
if(n == 0){} else { z = 1; }Rewrite that into an acceptable form that does the same thing. Answer
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
|