The return statement

A return statement ends the processing of the current function and returns control to the caller of the function.

Read syntax diagramSkip visual syntax diagramreturn statement syntax
             '-(-'              '-)-'

A value-returning function should include a return statement, containing an expression. C only If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues a warning message. C++ If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message.

If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.

For a function of return type void, a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered. In other words, an implicit return takes place upon completion of the final statement, and control automatically returns to the calling function. C++ If a return statement is used, it must not contain an expression.

Examples of return statements

The following are examples of return statements:

return;            /* Returns no value            */
return result;     /* Returns the value of result */
return 1;          /* Returns the value 1         */
return (x * x);    /* Returns the value of x * x  */

The following function searches through an array of integers to determine if a match exists for the variable number. If a match exists, the function match returns the value of i. If a match does not exist, the function match returns the value -1 (negative one).

int match(int number, int array[ ], int n)
   int i;

   for (i = 0; i < n; i++)
      if (number == array[i])
         return (i);

A function can contain multiple return statements. For example:

void copy( int *a, int *b, int c)
   /* Copy array a into b, assuming both arrays are the same size */

   if (!a || !b)       /* if either pointer is 0, return */

   if (a == b)         /* if both parameters refer */
      return;          /*    to same array, return */

   if (c == 0)         /* nothing to copy */

   for (int i = 0; i < c; ++i;) /* do the copying */
      b[i] = a[1];
                       /* implicit return */

In this example, the return statement is used to cause a premature termination of the function, similar to a break statement.

An expression appearing in a return statement is converted to the return type of the function in which the statement appears. If no implicit conversion is possible, the return statement is invalid.

Related information