Question

I want to return two or more values from a function and want to store those values into the main() function. I'm trying to do this by following code.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num1, num2, s, p;
    printf("Enter tow numbers: ");
    scanf("%d %d", &num1, &num2);
    p = function(num1, num2);
    s = function(num1, num2);
    printf("Sum is: %d\nProduct is: %d", p, s);
    return 0;
}

int function(int x, int y)
{
    int sum, product;
    sum = x+y;
    product = x*y;
    return product, sum;
}

If I enter two numbers, say 5 2 I want my result to be:

Sum is: 7
Product is: 10

But I'm getting 7 for both. How can I get my desired output?

Was it helpful?

Solution

C does not permit you to define a function which returns multiple types or multiple instances of a single type. You can however bundle variables of similar or disparate types together into a new user-defined type using a struct. In this case, you would do something like:

#include <stdio.h>
#include <stdlib.h>

typedef struct myStruct {
    int sum;
    int product;
} myStruct;

myStruct function(int x, int y) {
    myStruct val;
    val.sum = x+y;
    val.product = x*y;
    return val;
}

int main() {
    int num1, num2;
    myStruct result;
    printf("Enter tow numbers: ");
    scanf("%d %d", &num1, &num2);
    result = function(num1, num2);
    printf("Sum is: %d\nProduct is: %d", result.sum, result.product);
    return 0;
}

Also, while your program above is syntactically correct, the , in the return of your function has the result of only returning the last value in the collection of comma separated values. Normally the , isn't used in conjunction with a return; it can be quite handy when used in a for loop however.

OTHER TIPS

Another possible solution is to expect the product and sum values on arguments, like this:

#include <stdio.h>
#include <stdlib.h>

void function(int x, int y, int *p, int *s);

int main()
{
    int num1, num2, s, p;
    printf("Enter tow numbers: ");
    scanf("%d %d", &num1, &num2);
    function(num1, num2, &p, &s);
    printf("Sum is: %d\nProduct is: %d", s, p);
    return 0;
}

void function(int x, int y, int *p, int *s)
{
    *s = x+y;
    *p = x*y;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top