7D. Return Statements


Returns in non-void functions

A function with a non-void return type must return an answer no matter what its parameters are. If a function sometimes forgets to return a result, you will get a warning (if you have requested warnings). I compiled a small program containing the following function definition.

  int sometimes(int x)
  {
    if(x > 0) 
    {
      return 2*x;
    }
  }
Compiling that using g++ -Wall leads to the following error.
test.cpp: In function 'int sometimes(int)':
test.cpp:11:1: warning: control reaches end of non-void function [-Wreturn-type]
Clearly, if x ≤ 0, sometimes does not return an answer.


You can return any expression

A return-statement can return the value of any expression that has the correct type. You do not need to store a value into a variable so that you can return it. For example

  result = 3*x + 1;
  return result;
can be expressed more succinctly as
  return 3*x + 1;

The standards require you not to store a value in a variable just so that you can return it.

Recall that the standards require you not to use the value of an assignment as an expression, except in a multiple assignment. The standards explicitly require you not do use an assignment as an expression in a return statement. Do not write

  return result = f(x);


Returns in void functions

A void function typically does not contain a return-statement. When it reaches the end of its body, it automatically returns. If you want to force a void function to return at a place other than at the end of the body, use statement

  return;
For example, a function might return immediately if its parameter is not suitable, as in:
  void sample(int r)
  {
    if(r < 0)
    {
      printf("Negative parameter passed to sample\n");
      return;
    }

    ...
  }
But do not use return; in a place where it is not needed because the body would return anyway without doing anything more. The coding standards require that.

There is no value of type void, and if E is an expression of type void, it makes no sense to write

  return E;
Since that makes no sense, the standards disallow it.