Why does an expression i = 2
return 2? What is the rule this is based on?
printf("%d\n", i = 2 ); /* prints 2 */
I am in C domain after spending long time in Java/C#. Forgive my ignorance.
The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c). So here, readLine() will be executed, and its return value stored in line . That stored value is then checked against null , and if it's null then the loop will terminate.
It assigns value to t variable (and in your code t is reference type so the change is visible outside), and then return value of t variable.
An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. When the statement is executed, the expression is evaluated and the resulting value is stored in the target.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With