When I compile this program with the clang compiler and then run it, I get this output:
sum = 9
product = 6
sum - product = 6 - 6 = 0
and when I compile it with the gcc compiler and run it, the program terminates with a segmentation fault. Why is this?
Another question, why does *sum
have the value 6 in this part of the code?:
printf("sum - product = %d - %d = %d\n",
*sum, *product, *sum - *product);
Also, why does *sum - *product
produce the value 0?
Here is the program:
/***********************************************************************
* This program will add two numbers and then it will multiply two other
* numbers. Finally, it will subtract the second result from the first
* result.
***********************************************************************/
#include <stdio.h>
int *add(int a, int b) {
int result = a + b;
return &result;
}
int *multiply(int p, int q) {
int result = p * q;
return &result;
}
int main() {
int *sum = add(4, 5);
printf("sum = %d\n", *sum);
int *product = multiply(2, 3);
printf("product = %d\n", *product);
printf("sum - product = %d - %d = %d\n",
*sum, *product, *sum - *product);
return 0;
}