Questions about pointers

The following code gives an output of 4111
1
2
3
int list[] = { 1, 2, 3, 4, 5, 6, 7};
int *p = list;
std::cout << *(p+3) << *++p << *--p << *p << std::endl;


I have difficulty in understanding the 2nd and 3rd 1. Can someone explain it? Thanks in advance.
Last edited on
What you're doing is sort of illegal and has undefined output, which is why it's hard to understand.

You can't modify a variable (p) and read it multiple times in the same instruction because the compiler is free to rearrange the order of those writes/reads however it sees fit.

Try this instead:

1
2
3
4
std::cout << *(p+3);
std::cout << *++p;
std::cout << *--p;
std::cout << *p << std::endl;
Last edited on
What you are doing has undefined behaviour. The compiler is not allowed to modify a variable more than once between sequence points:

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15
Actually it was an interview question I was asked many years ago. Another such an illegal example is:
 
++++p; 


where p is a pointer.
Why ++++p is illegal?
Topic archived. No new replies allowed.