Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Returning a value from function

We can return a value of any type from a function, back to the caller function.

For that, we must declare a suitable return type in the function header.

If a function does not return any value, then the return type of function must be a void.

A function gets terminate at the line where return keyword is used.

If return keyword is not used in the function, the function is executed till the end.

Note

Type of the value returned by a function should match with the return type declared in the function header.
The type of the variable receiving the returned value should also match with the return type of function.

Example

#include <stdio.h>
int addition(int a,int b); 
int main()
{
    int answer;
    answer = addition(10,20);
    printf("Addition = %d",answer);
    return 0;
}

int addition(int a,int b) 
{
    int sum = a+b;
    return sum;
}

Output

Addition = 30

For a better understanding of the above program look at the diagram shown below:

C Programming Language return statement Working

The value of int variable sum is returned from addition() function to main() function (caller function).
It is then assigned to the int variable answer.

We can also use an expression with the return statement.

Example

#include <stdio.h>
int addition(int a,int b); 
int main()
{
    int answer;
    answer = addition(10,20);
    printf("Addition = %d",answer);
    return 0;
}

int addition(int a,int b) 
{
    return (a+b);
}

Output

Addition = 30

 

Leave a reply