Is there an advantage to having an 'else' following a block which ends with a 'return' or is it simply out of habit
int foo (int a)
{
if(a==0)
{
return false;
}
else
if(a==1)
{
return true;
}
else
{
}
return -1;
}
just curious
This is purely a style choice, or perhaps a misunderstanding that else
is required for every if
.
If all the if
blocks contain return
, there's no technical difference between putting the remaining code in a final else
block or putting it after the final else if
block in the chain; the same code should be generated. And an empty else
block has no effect at all.
Some programmers may prefer to use the else
block for stylistic reasons, it makes the parallel structure clear.
There's also no technical reason to use else if
when all the if
blocks return. There are some proponents of "else-less" programming who would write the above function as
int foo (int a)
{
if(a==0)
{
return false;
}
if(a==1)
{
return true;
}
return -1;
}
On the other hand, many programmers prefer a chain of else if
to make it clear that these are mutually exclusive conditions. Then you don't have to look into the bodies to see that they all return.