How to Return Two or More Values from a Function in C Language

How to Return Two or More Values from a Function in C LanguageMultiple return valuesIn C language, a function can generally return only one value by default. So, how can we design a function to return two or more values?Example of a standard library functionBefore that, let’s recall a standard library function in C language that we previously introduced, ldiv(). This function can be used to perform division operations on parameters of type long int and returns a value of type ldiv_t, which is a structure containing two members: quot and rem, representing the quotient and remainder of the division operation, respectively.Thus, we can also borrow the method of using structures in C language to design a function that can return multiple values (which actually still returns one). Of course, there are many other methods, but we will only introduce this one for now.Designing a function to return multiple values using structuresThe following example code first defines a structure containing two members: the length of the array and the average. Then, it designs a function that can be used to calculate the length and average of an array:

#include <stdio.h>
struct arrFeature{
    int sum;
    float average;
};
struct arrFeature coutArr(int arr[], int size){
    struct arrFeature feature;
    int sum = 0;
    for(int i = 0; i < size; i++){
        sum += arr[i];
    }
    feature.average = ((float)sum)/size;
    feature.sum = sum;
    return feature;
}
int main() {
    int arr[3] = {1,2,3};
    struct arrFeature feature = coutArr(arr,3);
    printf("The total sum of the array elements is: %d, average is: %.1f", feature.sum, feature.average);
    return 0;
}

After compiling and running, the output is:

The total sum of the array elements is: 6, average is: 2.0

Please open in the WeChat client

Disclaimer: The content is for reference only and does not guarantee accuracy. It should not be used as the basis for any decision!

Leave a Comment