I'm very new to programming and I'm having a hard time wrapping my mind around a couple of example problems.
First of all, my understanding is that ++x is postfix (meaning you add one and then display the new number) and x++ is prefix (meaning you display the number and then add one). Is this correct?
Now for the sample problems I've been looking at:
1 2 3 4 5 6 7 8
What will each of the following program segments display?
1) x = 2;
y = x++;
cout << x << " " << y;
2) x = 2;
y = ++x;
cout << x << " " <<y;
For number 1, I thought x=2 y=2 and for number 2, I got x=2 and y=3
However, I think both of these wrong. Can someone please explain why? Thank you and I apologize in advance if I'm not using the correct terms.
#include <iostream>
int main()
{
struct A // note: increment and assignment have observable side effects
{
A& operator++ () { std::cout << "then prefix increment => " ; return *this ; }
A operator++ (int) { A temp(*this) ; std::cout << "first postfix increment => " ; return temp ; }
A& operator= ( const A& ) { std::cout << "and finally assignment\n" ; return *this ; }
};
A x ;
A y ;
y = ++x++ ; // note that this wouldn't compile if the type of x were int
// because x++ which is parsed first results in a prvalue
// parsed as y = ( ++ (x++) )
}
first postfix increment => then prefix increment => and finally assignment