So, I was learning about the operators, and in particular, about binary operators.
In the following code:
int x=9;
x=-x;
cout<<x; // prints as -9
x= x;
cout<<x; //prints as -9
the question is why not as 9 or 9(contextual) than -9 ? why it works like this ?
CodePudding user response:
x=-x;
means assign to x
value which is negative to current x
.
x= x;
means assign to x
value which is promoted to type int
which is already an int
. Since in this step x
already has value -9
from previous operation nothing is changed and again -9
is printed.
Here are some docs.
CodePudding user response:
x=-x
, or to make it more readable x = -x
, is basically operation of reversing the sign of x
.
x = x
, is a trivial operation, since it copies x
into x
, since in previous operation the sign was reversed,x
is -9
, so now -9
is copied into x
.
CodePudding user response:
int x=9;
x=-x; //What is this for ? you mean x = x - 1 ? In this case syntax should be x -= x same for expression.
cout<<x; // prints as -9
x= x;
cout<<x; //prints as -9
If above expressions are correct, but you're asking about -9 as end answer here is solution.
line 1: init x with 9.
line 2: assigned x with -(minus) of x which is -9
line 4: assigned x with (plus) of x which is (-9) equals -9
CodePudding user response:
Its a simple math problem. minus times a plus is a minus hence , a plus times a minus is still a minus. This is the easiest way to look at it.