#include <stdio.h>
int ∗addition(int a, int b){
int c = a + b ;
int ∗d = &c ;
return d ;
}
int main (void) {
int result = ∗(addition(1, 2));
int ∗resultptr = addition(1, 2);
printf(”result = %d\n”, ∗resultptr);
printf(”result = %d\n”, result);
return 0 ;
}
This will give the correct answer. But it's strange that once I have interchanged the order of the last two printf()s, abnormal answer will be given.
printf(”result = %d\n”, result);
printf(”result = %d\n”, ∗resultptr);
Why is that? Is it because some internal implementations of printf()?
I have opened the -Wall option but no warning displayed.
Thank you for your answers! It's the first question for me on stackoverflow.
But why reverse the order will give different answers? If it's due to the undefined behavior of returning an local variable, why the first program gives the correct answer but the second can't, while the only difference is the order of printf()?