Given the following class:
class Foo { public volatile int number; public int method1() { int ret = number = 1; return ret; } public int method2() { int ret = number = 2; return ret; } }
and given multiple threads calling method1()
and method2()
concurrently on the same Foo
instance, can a call to method1() ever return anything other than 1?
The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
The assignment operators in C and C++ return the value of the variable being assigned to, i.e., their left operand. In your example of a = b , the value of this entire expression is the value that is assigned to a (which is the value of b converted into the type of a ).
What is the difference between = (Assignment) and == (Equal to) operators. The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.
The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value.
I think the answer depends on the compiler. The language specifies:
At run-time, the result of the assignment expression is the value of the variable after the assignment has occurred.
I suppose that theoretically the value could be changed before the second (leftmost) assignment occurs.
However, with Sun's javac compiler, method1
will will turn into:
0: aload_0 1: iconst_1 2: dup_x1 3: putfield #2; //Field number:I 6: istore_1 7: iload_1 8: ireturn
This duplicates the constant 1
on the stack and loads it into number
and then into ret
before returning ret
. In this case, it won't matter if the value stored in number
is modified before assignment to ret
, because 1
, not number
is being assigned.
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