Sunday, July 7, 2013

Return in C

Return Statement is written at the end of a subroutine to get back to the called routine. This return statement is used to return some value to the called function. In C, we use the return statement like this,
return(x) or return x;
Both the usages result the same, they return the value x;

Once a return statement is used, the function gets back to the called function and doesn't execute the lines of code under the return. So return statement is used generally at the bottom of the function.



A return statement can't return more than one value. What happens if we use more than one value in a return statement??? Let us check out now.

If we use the return statement as
return 0 5;
It returns in an error as it can't take more than one value. But if we use a statement like,
return(0,5);
It doesn't return an error. Instead of giving an error, it takes the last value we pass, i.e., it takes the value 5 and returns to the called function.

All this can be done only if a function has a return type, If a function doesn't have a return type, in C, it is generally an integer. So we can return the integer value.

If the return type is void, then we can't return a value. We can use an empty return statement but can't return a value.

What happens if we return a float even if the return type is float????

It just returns the integer part of the value. To know more, click here