0

Say I have a void-returning function,

void foo(void)
{
    // code
}

or

void foo(void)
{
    // code
    return;
}

I wonder which one is better in practice? Are there any potential problems in the first one?

Edward Karak
  • 10,340
  • 8
  • 41
  • 68
nalzok
  • 11,870
  • 17
  • 57
  • 105

2 Answers2

1

Both cases are completely equivalent.

In the second example return; is completely redundant and I see no reason to use it.

Community
  • 1
  • 1
HolyBlackCat
  • 45,832
  • 5
  • 81
  • 134
1

In your cases above, it is not necessary to write the return since both are equivalent.

There are cases, however, where you want to write return because your function paths are branched and you want to have early return in one or more branches (but not all branches) for good reasons (such as simplification or readibility)

For example, consider the following case:

void foo(){
    if (a){
        //do something
    } else {
        //do something else
    }
}

The function paths are branched and suppose you want to reduce the indentation of your code by removing else block. Then you could write the code above with early return as follow:

void foo(){
    if (a){
        //do something
        return;
    }
    //do something else    
}

In such case, you may consider of using early return in a void-returning function.

Ian
  • 28,526
  • 18
  • 60
  • 94