I'm new to C++. I was practicing returning pointer from function when I ran into this printf problem. Putting 2 printf back to back produced some weird results.
Two versions of an add function.
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b) {
int c = a + b;
return c;
}
int* add2(int* a, int* b) {
int c = *a + *b;
return &c;
}
In main, if I put two printf back to back, the first one returns the right value, while the second one returns random numbers.
int main() {
int x = 2, y = 4;
int z1 = add(x, y); // Pass by value function, return value
int* z2 = add2(&x, &y); // Pass by reference function, return pointer
// This causes the problem
printf("%d\n", z1); // 6
printf("%d\n%d\n", *z2); // some random large number
return 0;
}
However, if I put both in the same printf, everything's fine.
printf("%d\n%d\n", z1, *z2);
Two printf of z1 also works fine.
printf("%d\n", z1); // 6
printf("%d\n", z1); // 6
Is it something related to pointers and how printf works?
I'm using Visual Studio 2019 Community Version default settings.