Basic Syntax

In the following code the output is:

-4

4

Why is the value of n not permanently changed to -4?


1
2
3
4
5
6
int n =4; 

cout << -n << endl;

cout << n;
Last edited on
It would be "permanently changed" if you would write

n = -n;

-4 is the value of expression -n. It is not the value of n itself. In fact -n can be written as 0 - n;. So why will n be changed? You can substitute 0 for some variable that has value 0. For example let assume that m is equal to 0. Then the previous expression can be rewritten as

m - n;

It would be strange if the value of n would be changed.
Last edited on
Ok. I suppose the confusion arose from the fact the below causes a change to the variable. I envisaged that the change to n from the below arose from an operation in the same way that the change from -n is an operation (as you suggest (0-n)).

So basically Unary operators don't change variables. Thanks.

1
2
3
4
5

--n;

n++;

Last edited on
Now that you mention, the pre/post increment/decrement operators do differ from the unary sign operators.
Topic archived. No new replies allowed.