Post fix increment

Can somebody help explain the internals of what's happening here.

int num = 5;
int num1 = -num++;
cout << num << " " << num1;

The above I understand, -num makes a copy which gets assigned to num1, then num gets incremented. The output is -5 6.

The below code doesn't compile and I don't understand why

int num3 = 5;
int num4 = (-num)++;

compiler: error lvalue required as increment operand. However, the above code does work with an overloaded operator ++ for my user defined types?

1
2
3
int num = 5;
int num1 = -num++;
cout << num << " " << num1;

Is approximately:
1
2
3
4
5
int num = 5;
const int tmp = num;
int num1 = -tmp;
++num;
cout << num << " " << num1;



1
2
3
int num = 7;
int num1 = (-num)++;
cout << num << " " << num1;

Is approximately:
1
2
3
4
5
int num = 7;
const int tmp = -num;
int num1 = tmp;
++tmp; // error
cout << num << " " << num1;


The (-num) is a temporary value. Effectively -7. A constant. There is no increment for integer constants.

Your custom types:
1
2
Foo num = 7;
Foo num1 = (-num)++;

What type does Foo::operator- () return?
Last edited on
Foo::operator-()

returns a negative copy of type foo
keskiverto thanks for the reply,

So the brackets around (-num) pretty much say increment this value, which is a copy. Unlike in the first example where the copy gets returned then the original value gets incremented?

Topic archived. No new replies allowed.