What does an assignment return?
It evaluates to 2
because that's how the standard defines it. From C11 Standard, section 6.5.16:
An assignment expression has the value of the left operand after the assignment
It's to allow things like this:
a = b = c;
(although there's some debate as to whether code like that is a good thing or not.)
Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too).
The rule is to return the right-hand operand of =
converted to the type of the variable which is assigned to.
int a;
float b;
a = b = 4.5; // 4.5 is a double, it gets converted to float and stored into b
// this returns a float which is converted to an int and stored in a
// the whole expression returns an int
It consider the expression firstly then print the leftmost variable.
example:
int x,y=10,z=5;
printf("%d\n", x=y+z ); // firstly it calculates value of (y+z) secondly puts it in x thirdly prints x
Note:
x++
is postfix and ++x
is prefix so:
int x=4 , y=8 ;
printf("%d\n", x++ ); // prints 4
printf("%d\n", x ); // prints 5
printf("%d\n", ++y ); // prints 9
- Assign the value 2 to i
- Evaluate the i variable and display it