Returning from a void function

Agnius Vasiliauskas picture Agnius Vasiliauskas · Jan 25, 2012 · Viewed 146.5k times · Source

Which is more correct way to return from function:

void function() {
  // blah some code
}

OR

void function() {
  // blah some code
  return;
}

Rationale for second way:

  1. It expresses developer intentions more clearly.
  2. It helps detecting function end at pre-compile time:

Suppose you have such scenario- you have bunch of functions and you must inject some code at the end of those functions. But for some reasons you don't want / or can't modify such huge amount of functions. What can you do about that ? Return & macro comes into play, for example:

#include<stdio.h>

#define MAX_LINES 1000
#define XCAT(a,b) a##b
#define CAT(a,b) XCAT(a,b)
#define return returns[__LINE__] = 1;\
        if (returns[__LINE__])\
           {printf("End of function on %d line.\n",__LINE__);}\
        int CAT(tmp,__LINE__); \
        if ((CAT(tmp,__LINE__)=returns[__LINE__], returns[__LINE__] = 0, CAT(tmp,__LINE__)))\
              return

static int returns[MAX_LINES];


void function1(void) {
    return;
}

void function2(void) {
    return;
}

int main()
{
    function1();
    function2();

    return 0;
}

Answer

William Morris picture William Morris · Jan 25, 2012

Neither is more correct, so take your pick. The empty return; statement is provided to allow a return in a void function from somewhere other than the end. No other reason I believe.