Currently I'm learning about pointers. I don't really understand what is happening the following line:
*p += a++ + (*p)++;
*p is a pointer to a. Before this line a equals 2. I expected actually that the final value would be 12. So first a will be incremented by 1. This will make a = 3, but also *p=3. When (*p)++ it will be incremented to 4 and also a will be 4. So the sum will be 4 += 4+4 --> 12.
This turns out to be wrong. So my question is: In which order are the operations happening? What is happening in the registers of the program? That explains this?
Nadine
#include <iostream>
#include <string>
int main()
{
int a = 1;
std::cout << "intitialisation a:"<< a << std::endl;
int b = 2;
int c = 3;
{
auto b = ++a + c++;
std::cout << "increment a in function:" << a << std::endl;
auto e = b;
c += ++b;
}
int* p = &a;
std::cout <<"value pointer:" << *p << std::endl;
int* q = &b;
++(*q);
std::cout << "value a before ++"<< a << std::endl;
std::cout << "value pointer before ++: " << *p << std::endl;
*p += a++ + (*p)++;
std::cout << "value a after ++"<< a << std::endl;
std::cout << "value pointer after ++: " << *p << std::endl;
}
output:
intitialisation a:1
increment a in function:2
value pointer:2
value a before ++2
value pointer before ++: 2
value a after ++9
value pointer after ++: 9