The if-else sequence is in many cases verbose and redundant. A cleaner alternative uses only an if-clause that is followed by a block with a return statement, without a following else-block.
The "else" part is implicit: anything that isn't included in the true-case block. Consider:
cond = true;
return cond; //else isn’t required
This code can be further simplified as:
return false; //else isn’t required
takes a little time to getting used to two return statements in a row, but with
proper indentation and code compactness, the intent is clearer and safer. I use
else only if the condition isn't binary. In other words, when there are three
or more difference possible conditions. A fork()
call is a classic example. The returned pid value can be negative, zero or
if (childpid==0) //zero value
printf("this is the child process");
exit(0); //terminate the child process
else if(childpid>0) //positive value
printf("this is the parent process");
else //third option: negative value
Notice that in the latter example, not every option leads to a break, therefore you need to use the last else to avoid "falling off" the previous condition of a positive value.
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.