You pass uninitialized pointers as arguments to function prod_and_sum
. Your code has undefined behavior as the function prod_and_sum
dereferences these uninitialized pointers to store the sum and product*. The program can stop or continue or produce other side effects... In your case, it seems to stop silently.
The behavior is undefined, there is no point trying to understand what happens... You should just correct the problem by passing the addresses of int
variables where you want the results stored:
#include <stdio.h>
void prod_and_sum(int a, int b, int *p, int *s) {
*p = a * b;
*s = a + b;
}
int main(void) {
int prod, sum;
prod_and_sum(5, 10, &prod, &sum);
printf("sum: %d, product: %d\n", sum, prod);
return 0;
}
Note that you can also return multiple values by making them fields of a structure that you return:
#include <stdio.h>
typedef struct prod_sum { int prod, sum; } prod_sum;
prod_sum prod_and_sum(int a, int b) {
return (prod_sum){ a * b, a + b };
}
int main(void) {
prod_sum res = prod_and_sum(5, 10);
printf("sum: %d, product: %d\n", res.sum, res.prod);
return 0;
}
* as a matter of fact, just passing the values of uninitialied pointers has undefined behavior, but attemting to dereference them is more likely to cause a visible effect such as a segmentation fault.