Our organization has a required coding rule (without any explanation) that:
if … else if constructs should be terminated with an el
Most the time when you just have a single if
statement, it's probably one of reasons such as:
Example
void print (char * text)
{
if (text == null) return; // guard check
printf(text);
}
But when you do if .. else if
, it's probably one of reasons such as:
And in case your if .. else if
covers all possibilities, in that case your last if (...)
is not needed, you can just remove it, because at that point the only possible values are the ones covered by that condition.
Example
int absolute_value (int n)
{
if (n == 0)
{
return 0;
}
else if (n > 0)
{
return n;
}
else /* if (n < 0) */ // redundant check
{
return (n * (-1));
}
}
And in most of these reasons, it's possible something doesn't fit into any of the categories in your if .. else if
, thus the need to handle them in a final else
clause, handling can be done through business-level procedure, user notification, internal error mechanism, ..etc.
Example
#DEFINE SQRT_TWO 1.41421356237309504880
#DEFINE SQRT_THREE 1.73205080756887729352
#DEFINE SQRT_FIVE 2.23606797749978969641
double square_root (int n)
{
if (n > 5) return sqrt((double)n);
else if (n == 5) return SQRT_FIVE;
else if (n == 4) return 2.0;
else if (n == 3) return SQRT_THREE;
else if (n == 2) return SQRT_TWO;
else if (n == 1) return 1.0;
else if (n == 0) return 0.0;
else return sqrt(-1); // error handling
}
This final else
clause is quite similar to few other things in languages such as Java
and C++
, such as:
default
case in a switch statementcatch(...)
that comes after all specific catch
blocksfinally
in a try-catch clause