I wrote C ++ code as follows:
#include <iostream>
using namespace std;
int main() {
int i = 2;
int i2 = 0;
void *pi = &i - 1;
cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
printf("by printf - the value of *pi is: %d\n", *(int*)pi);
printf("the address of pi is: %p\n", pi);
printf("the address of i2 is: %p\n", (void*)&i2);
printf("the value of i2 is: %d\n", i2);
return 0;
}
and output:
by cout - the value of *pi is: 0
by printf - the value of *pi is: 0
the address of pi is: 0029fe94
the address of i2 is: 0029fe94
the value of i2 is: 0
Now, if I delete the statement that will print the address.
#include <iostream>
using namespace std;
int main() {
int i = 2;
int i2 = 0;
void *pi = &i - 1;
cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
printf("by printf - the value of *pi is: %d\n", *(int*)pi);
printf("the value of i2 is: %d\n", i2);
return 0;
}
now output:
by cout - the value of *pi is: 2004212408
by printf - the value of *pi is: 2004212408
the value of i2 is: 0
Please note that the meaning was completely different.
update: If after printing add the following task:
#include <iostream>
using namespace std;
int main() {
int i = 2;
int i2 = 0;
void *pi = &i - 1;
cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
printf("by printf - the value of *pi is: %d\n", *(int*)pi);
pi = &i2;
printf("the value of i2 is: %d\n", i2);
return 0;
}
the output was normal again:
by cout - the value of *pi is: 0
by printf - the value of *pi is: 0
the value of i2 is: 0
use "g ++ -std = C ++ 11 -pedantic -Wall" to compile, version 4.9.2.
Why could this happen?