Write a program that returns 3 numbers from a function using a structure?

A function in C can return only one value. If we want the function to return multiple values, we need to create a structure variable, which has three integer members and return this structure.

Program: Program with a function to return 3 values

//sample structure which has three integer variables.
struct sample 
         int a, b, c;
//this is function which returns three values.
struct sample return3val() 
         struct sample s1;
         s1.a = 10;
         s1.b = 20;
         s1.c = 30;
        //return structure s1, which means return s1.a ,s1.b and s1.c
        return s1;
int main() 
        struct sample accept3val;
        //three values returned are accepted by structure accept3val.
        accept3val = return3val();
        //prints the values
        printf(" \n %d", accept3val.a);
        printf("\n %d", accept3val.b);
        printf(" \n %d", accept3val.c);
       return 0;



In this program, we use C structure to return multiple values from a function. Here we have a structure holding three int variables and a function which returns it. 'return3val' is a function which assigns 10, 20, 30 to its integer variables and returns this structure. In this program, 'accept3val' is a structure used to accept the values returned by the function. It accepts those values and shows the output.

No comments:

Post a Comment