return statement C

The return is a jump statement. When the return statement is executed in a function, then it terminates the execution of the function and returns control to its caller function.

Syntax:

return;
return expression;

How does the return statement work?

When a function call to another function, then execution of the calling function is paused. The control is transfer to the called function from the calling function. The return statement returns the control to the calling function (terminates the execution of the called function) and now execution of the calling function is resumed.

Let see an example,

In below program, when the main function calls addNumbers, then “main” is paused and addNumbers starts.

The addNumbers calculate the sum of the number from 1 to 100 and when control reaches to the statement return sum; then terminate the execution of addNumbers and control is transferred back to the main function.

Output: 5050

 

Some important point related to the return statement in C

 

1.  A function may have any number of return statements.

You can see below the 1D dynamic array in which I am using return two times.

 

 

2. We must not use return statement with an expression in a function whose return type is void.

Output: [Warning] ‘return’ with a value, in function returning void

 

3. We must use the return statement without an expression in a function whose return type is void.

 

4. According to C standard, If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function. See the below example,

Output: Value of Sample  = 4