The Return Statement in C

If a function has to return a value to the calling function, it is done through the return statement. It may be possible that a function does not return any value; only the control is transferred to the calling function.

The syntax for the return statement is:

return (expression);

We have seen in the square( ) function, the return statement, which returns an integer value.

Points to remember:

  • You can pass any number of arguments to a function but can return only one value at a time.

For example, the following are the valid return statements

(a) return (5);
(b) return (x*y);

For example, the following are the invalid return statements

(c) return (2, 3);
(d) return (x, y);

  • If a function does not return anything, void specifier is used in the function declaration.

For example:

void square (int no)
{
int sq;
sq = no*no;
printf (“square is %d”, sq);
}

• All the function’s return type is by default is “int”, i.e. a function returns an integer value if no type specifier is used in the function declaration.

Some examples are:

(i) square (int no); /* will return an integer value */
(ii) int square (int no); /* will return an integer value */
(iii) void square (int no); /* will not return anything */

• What happens if a function has to return some value other than integer? The answer is very simple: use the particular type specifier in the function declaration.

For example, consider the code fragments of function definitions below:

1) Code Fragment - 1

char func_char( …….. )
{
…………….
…………….
……………
}

2) Code Fragment - 2
float func_float (……..)
{
float f;
…………..
…………..
…………..
return(f);
}

Thus from the above examples, we see that you can return all the data types from a function, the only condition being that the value returned using return statement and the type specifier used in function declaration should match.

• A function can have many return statements. This thing happens when some condition based returns are required.

For example,

/*Function to find greater of two numbers*/
int greater (int x, int y)
{
if (x>y)
return (x);
else
return (y);
}

• And finally, with the execution of the return statement, the control is transferred to the calling function with the value associated with it.

In the above example if we take x = 5 and y = 3, then the control will be transferred to the calling function when the first return statement will be encountered, as the condition (x > y) will be satisfied. All the remaining executable statements in the function will not be executed after this returning.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: