return statement in C

Quick links

A function is a collection of statements grouped together to do some specific task. It may return a value. However, in no case a function will return more than one value. What does it mean by returning a value and where it is returned? To understand this let us consider an example.

Suppose I am the boss of a company. I assigned an audit task to one of my employee. Consider the audit task as a function. Employee will complete the task (execute the function) and return the audit report back to the boss (i.e. me). Similarly, function returns a value and program control back to the caller function.

Returning a value from function

Use of return statement

return statement terminates a function and transfer program control to its caller function. Optionally it may return a value to the caller. You can use the return statement anywhere inside a function.

Note: Once a function returned program control to the caller. The function cannot get the control back.

Syntax of return statement

return expression;
  • return keyword transfers program control to the caller.
  • expression is optional, used to return result of a valid C expression to the caller.

Note: The function return type and returned value type (data type) of the function must be same.

Returning a value from function

Example program to use return statement

Write a C program to input two numbers from user. Write a function to find maximum between two given two numbers and return the maximum value.

/**
 * C program to find maximum between two numbers using function
 */

#include <stdio.h>

/* Function declaration */
int max(int num1, int num2);

int main()
{
    int num1, num2, maximum;
    printf("Enter two numbers: ");
    scanf("%d%d", &num1, &num2);

    /*
     * Call max function with arguments num1 and num2
     * Store the maximum returned to variable maximum
     */
    maximum = max(num1, num2);

    printf("Maximum = %d", maximum);

    return 0;
}

/* Function definition */
int max(int num1, int num2)
{
    int maximum;

    // Find maximum between two numbers
    if(num1 > num2)
        maximum = num1;
    else
        maximum = num2;

    // Return the maximum value to caller
    return maximum;
}

Output -

Enter two numbers: 10 20
Maximum = 20

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>