I am taking my first steps in C++ having a good background in Java. I need to clear out some peculiarities of the ++ operator in C++. Consider the following program:
#include <iostream>
using namespace std;
void __print(int x, int *px) {
cout << "(x, *px) = (" << x << ", " << *px << ")" << endl;
}
int main() {
int x = 99;
int *px = &x;
__print(x, px);
x++; __print(x, px);
x = x + 1; __print(x, px);
*px = *px + 1; __print(x, px);
*px++; __print(x, px);
return 0;
}
Surprisingly to me, the program prints:
(x, *px) = (99, 99)
(x, *px) = (100, 100)
(x, *px) = (101, 101)
(x, *px) = (102, 102)
(x, *px) = (102, 134514848)
It seems that *px = *px + 1 does not have the same effect on *px as on x. But aren’t these things the same??? Isn’t it *px == x?
the
*operator works after the++so it returns the value of a wrong address. the operator precedence is important to know in c++. take a look at this :http://en.cppreference.com/w/cpp/language/operator_precedence
Add parentheses to change operator precedence, for example:
result: