I accidentally discovered this
Is this a feature or just the way the interpreter works, if is a feature how it is called ?
Do other languages have this feature ?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
This type of feature is typically known as "multiple assignment." Many languages have this type of feature.
This type of feature is typically known as "chained assignment." Languages that consider assignment to be expressions have this type of feature.
Multiple assignment typically means something else, e.g. Python:
a, b, c, d, e, f = [2, 2, 2, 2, 2, 2]
This type of syntax structure can be referred to as multiple assignment. In the context of Python, this is also known as unpacking.
The astute programmer might note that this is related to multiple return values:
def f(): return [1, 2, 3] a, b, c = f()
There are a large number of languages that support chained assignment or multiple assignment in different ways.
C, C++, Java, and C# support the syntax you provided. VB does not support chained assignment (since assignment is a statement and not an expression like in the C family). Go supports multiple assignment similarly to Python, e.g. a swap:
a, b = b, a
I believe Lua supports multiple assignment and multiple return values. It can be done in a Lisp but there's usually a better way to go about it.
Basically, most languages support either of these features in some way.
Assignments like these are OK for simple objects. For others, it can lead to undesirable side effects. In linked list the example below, in the line:
last = last.nxt = Item(2)
We may expect that Item(1).nxt points to Item(2) and last points to Item(2) However, we end up with a circular reference where Item(2).nxt points to itself.
class Item(object): def __init__(self, value): self.value = value self.nxt = None def __str__(self): return 'self: id(self): %d, value: %s, nxt: %d' % (id(self), \ str(self.value), id(self.nxt)) prev = last = Item(1) print prev >>> self: id(self): 140382915976272, value: 1, nxt: 9568656 print last >>> self: id(self): 140382915976272, value: 1, nxt: 9568656 print id(None) >>> 9568656 last = last.nxt = Item(2) print prev >>> self: id(self): 140382915976272, value: 1, nxt: 9568656 print last >>> self: id(self): 140382915975120, value: 2, nxt: 140382915975120
It is a feature of the language, the = statement evaluates the statement to its right and assigns that value to the variable on the left.
In Python a statement like a, b = 1,2 is also legal. That is called multiple assignment. See Python Docs I don't know of a special term for the a=b=2 structure though. It is just multiple assignments on the same line.