• Home
  • 6.5 Ignoring a Function Return Value

6.5 Ignoring a Function Return Value

View Categories

6.5 Ignoring a Function Return Value

A function that returns a value can be called without storing or otherwise using that value. The function still executes, but its returned value is discarded by the caller.

#include <stdio.h>

int calculateSum(int a, int b)
{
    printf("Calculating sum\n");
    return a + b;
}

int main(void)
{
    calculateSum(10, 20);

    int result = calculateSum(5, 7);

    printf("Stored result = %d\n", result);

    return 0;
}

Example Output #

Calculating sum
Calculating sum
Stored result = 12

Explanation #

The first function call:

calculateSum(10, 20);

executes the function, prints the message, and returns 30. The caller does not use the returned value.

The second call:

int result = calculateSum(5, 7);

executes the same function and stores its returned value, 12, in result.

Using and Ignoring Return Values #

Function call Behavior
calculateSum(10, 20); Executes the function and discards its return value
int result = calculateSum(5, 7); Stores the returned value
printf("%d\n", calculateSum(2, 3)); Passes the returned value to another function

Ignoring a return value is valid C syntax, even when the function’s return type is not void. However, the return value may indicate whether an operation succeeded or failed, so discarding it can be inappropriate when the result needs to be checked.

For example, functions such as scanf() and malloc() return information that often must be checked to ensure correct program behavior.

Powered by BetterDocs

Leave a Reply

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