• Home
  • 6.4 Function Return Values

6.4 Function Return Values

View Categories

6.4 Function Return Values

A function return value is the value sent back to the calling code using the return statement. The function’s return type determines the type of value it can return.

#include <stdio.h>

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

float calculateAverage(int total, int count)
{
    return (float)total / count;
}

int main(void)
{
    int sum = calculateSum(10, 20);
    float average = calculateAverage(sum, 4);

    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", average);

    return 0;
}

Example Output #

Sum = 30
Average = 7.50

Explanation #

The function calculateSum() returns an integer:

return a + b;

When called with 10 and 20, it returns 30. That value is stored in sum.

The function calculateAverage() returns a float:

return (float)total / count;

The cast converts total to float before division, so the division uses floating-point arithmetic rather than integer division.

Return Types #

Return type Example Description
int return 10; Returns an integer value
float return 3.5f; Returns a floating-point value
char return 'A'; Returns a character value
void return; Returns without providing a value

A function declared with a non-void return type must not be used as though it returns a valid value if execution reaches the end of the function without returning one. In C, reaching the closing brace of main() is equivalent to returning 0; this special rule does not apply to other non-void functions.

A return statement also terminates the current function immediately. Any statements following the executed return statement in that path are not executed.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *