Namespaces
Variants
Views
Actions

return statement

From cppreference.com
< c‎ | language
Revision as of 09:47, 12 May 2014 by Newatthis (Talk | contribs)

Terminates current function and returns specified value to the caller function.

Contents

Syntax

return expression ; (1)
return ; (2)

Explanation

1) Evaluates the expression, terminates the current function and returns the result of the expression to the caller (the value returned becomes the value of the function call expression). Only valid if the function return type is not void.
2) Terminates the current function. Only valid if the function return type is void.

If the type of the expression is different from the return type of the function, its value is converted as if by assignment to an object whose type is the return type of the function, except that overlap between object representations is permitted:

struct s { double i; } f(void); // function returning struct s
union { struct { int f1; struct s f2; } u1;
        struct { struct s f3; int f4; } u2; } g;
struct s f(void)
{
    return g.u1.f2;
}
int main(void)
{
// g.u2.f3 = g.u1.f2; // undefined behavior (overlap in assignment)
   g.u2.f3 = f();     // well-defined
}

If the return type is a real floating type, the result may be represented in greater range and precision than implied by the new type.

Reaching the end of a function other than main is equivalent to return;. Reaching the end of the main function is equivalent to return 0;.

Keywords

return

Example

#include <stdio.h>
 
void fa(int i)
{
    if (i == 2)
       return;
    printf("fa():   %d\n", i);
} /* implied return; */
 
int fb(int i)
{
    if (i > 4)
       return 4;
    printf("fb():   %d\n", i);
    return 2;
}
 
int main(void)
{
    fa(2);           /* returns, does nothing when i==2   */
    fa(1);           /* prints its argument, then returns */
    int i = fb(5);   /* 5>4, so returns 4                 */
    i = fb(i);       /* prints its argument, returns 2    */
    printf("main(): %d\n", i);
}

Output:

fa():   1
fb():   4
main(): 2