Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator ++ and pointers

Tags:

c++

pointers

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?

like image 584
Pantelis Sopasakis Avatar asked Aug 11 '26 04:08

Pantelis Sopasakis


2 Answers

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:

#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;
}

result:

(x, *px) = (99, 99)
(x, *px) = (100, 100)
(x, *px) = (101, 101)
(x, *px) = (102, 102)
(x, *px) = (103, 103)
like image 199
WeaselFox Avatar answered Aug 13 '26 03:08

WeaselFox


The problem is with operator precedence. Try (*px)++;

like image 30
AlefSin Avatar answered Aug 13 '26 05:08

AlefSin