Can some one explain the output of below code
int a=10;
a = a -= a+= a -= a += a;
output : 10
I am not able to get how it is giving 10?
a += a
means a = a + a
.
likewise, a -= a
means a = a - a
.
I am not sure which way is proper to start, but if I convert the given code from the right using above,
a += a > a = a + a;
a -= a += a > a = a - (a + a);
a+= a -= a += a > a = a + (a - (a + a ));
a -= a+= a -= a += a > a = a - (a + (a - (a + a)));
a = a -= a+= a -= a += a > a = a - a - a + a + a;
where -a -a + a + a
cancels each other, resulting a = a
, which is 10
.
There are multiple concepts at work here.
In programming languages, the associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses.
Assignment operator is right associative
operator meaning to evaluate an expression without parentheses with multiple assignment operators, we would began evaluation from right side. This determines the precedence.
Well technically we're talking about Addition assignment +=
and Subtraction assignment -=
, which is same as assignment operator after expansion.
a = a -= a+= a -= a += a;
is same as
a = (a -= (a+= (a -= (a += a))));
After you change the expression like that, it becomes clear how answer comes out to be 10
L-Value
is an expression which can appear in the left hand side of an assignment
operation in an expression according to the rules of a programming language, similarly for R-Value
an expression which can appear on the right hand side of assignment
.Many popular programming languages allow expression a = b
to be R-Value
expression, which returns value of L-Value
variable with the same type.
Note: All operators in expression have a return value and type like a function
.
In a = b
, a
is L-Value
and thus the return value and type is of a
So a = b = c
is equivalent to a = assign(b, c)
where TypeA assign(TypeA a, TypeB b)
function signature can represents the assignment operation in most cases.
TypeA assign(TypeA a, TypeB b)
Evaluation start from left to right for variables. What that means is during parsing parser will start replacing variables with their value from left to right.
For example in a += (a += a) => a = a + (a = a + a)
will become a = 10 + (a = 10 + 10)
before compiler starts to evaluate first operator.
First operator evaluated will be the one with the highest precedence in inner most bracket.
Keeping these rules in mind we can see the evaluation below
a = a -= a+= a -= a += a;
//after deciding precedence of operators
a = (a -= (a+= (a -= (a += a))));
//after addition assignment expantion
a = (a = a - (a = a + (a = a - (a = a + a))))
//First pass of parser
a = (a = 10 - (a = 10 + (a = 10 - (a = 10 + 10)))) //2nd pass, current a = 10
a = (a = 10 - (a = 10 + (a = 10 - (20)))) //3rd pass, current a = 20
a = (a = 10 - (a = 10 + (-10))) //4th pass, current a = -10
a = (a = 10 - (0)) //5th pass, current a = 0
a = 10 //6th pass, current a = 10