Home > Blogs > 30 C++ Tips in 30 Days: Tip # 5 something else

30 C++ Tips in 30 Days: Tip # 5 something else

By  Nov 24, 2007

Topics: Programming, C/C++

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:

{
 bool cond=false;
  if (p)
 {
  cond = true;
  return cond
 }
 return cond; //else isn’t required

This code can be further simplified as:

{
 if (p)
   return true;
 return false; //else isn’t required

It 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 positive: 

pid_t childpid=fork();
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
{
 printf("fork failed!");
 exit(1);
}

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.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.