*x++
is equivalent to
*(x++)
.
The value of x is some memory address. The form above changes the memory address first, and then looks at the value pointed to by that memory address. The problem is that if x is at address 2, nothing's at address 3: the above snippet looks at address 3. (that's why the output was garbage).
Note that in the context you used it above, the dereference itself has no purpose, since the result is ignored. Because the result was ignored in the context you used it,
*x++;
was equivalent to simply
x++;
, which changes the memory address (the value of x) and that's it.
(*x)++;
Looks at the value pointed to by x (i.e., the value at the memory address x contains) and adds one to it.
and also how do you fix the first function so the x is displayed in main function as it should be "incremented" |
Have you learned of "pass by reference" yet?
If you have, you should let the reference parameter x bind to the variable you want to change:
void increment(int& x) { x++; }
Then elsewhere you could call
1 2 3 4
|
int my_variable = 0;
std::cout << "before increment: " << my_variable << '\n'; // prints 0
increment(my_variable);
std::cout << "after increment: " << my_variable << '\n'; // prints 1
| |
If not, you'd have to accept the address of x and change the value it points to, assuming, of course, that the address you got was valid:
void increment(int* x) { (*x)++; }
Then elsewhere you could call
1 2 3 4
|
int my_variable = 0;
std::cout << "before increment: " << my_variable << '\n'; // prints 0
increment(&my_variable);
std::cout << "after increment: " << my_variable << '\n'; // prints 1
| |