The idea it was named after

Sunday, September 11, 2005

Now Multiple assignation really works

I've been hacking a bit the small example implementing multiple assigments in C++. The code is acually even a bit easier, as I have simplified the process. It's funny to see that depending on if you return void or nothing in the operator =, its precedence seems to change! At least in gcc which is the compiler I'm using.

Let's explain the modus operandi of the code; let's say we have the following statement:
a, b, c = d, e, f;

What happens?

  1. The operator = is called, for c = d. It initialices a static var called stage to 1, saves those two elements in two static pointers for later use and finally acts as if we wanted to do c = d;, because this is the only chance we have to do it, and if that's not the case, we'll fix it later. Finally, the operator returns d, reducing everything to this list of elements:
    a, b, d, e, f;


  2. The comma operator is called for a, b. We're in stage 1, everything is fine. The operator finds that the second element is still not d, so we are in the left part of the comma-separated list. It links a to b as in a linked list, and sets the static pointer actual to &a. actual stablishes which is the following var we want to assign. It was zero until now (the = operator initizalized it to zero).

  3. The comma operator is called for b, d. It detects that the second element is d when comparing it against the static var right. We are in the middle of the assigment! b is linked to c (that was saved in the satic pointer left), and it assigns d to a using actual. Finally it sets actual to the next element in the linked list, and the operator returns d.

  4. The same process is repeated again and again for d, e and e, f. It just continues retrieving elements from the linked list and setting them to the value of the second element of the operator (inside both operators, the first element is the pointer this and the second one is passed by reference as an argument: obj).


So there you go! Now the program doesn't need to treat a, b = c, d; as an special corner case. It just works =). The code is in the same place as before, but it's been updated.

0 Comments:

Post a Comment

<< Home