Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound assignment operators, what happens if the value is modified (in the meanwhile)?

Consider the following pseudocode (language agnostic):

int f(reference int y) {
   y++;

   return 2;
}

int v = 1;

v += f(v);

When the function f changes y (that is v) while evaluating v += f(v), is the original value of v "frozen" and changes to v "lost"?

v += f(v); // Compute the address of v (l-value)
           // Evaluate v (1)
           // Execute f(v), which returns 2
           // Store 1 + 2 
printf(v); // 3
like image 850
gremo Avatar asked Oct 21 '22 08:10

gremo


1 Answers

In most languages += operator (as well as any other compound assignment operator, as well as simple assignment operator) has right-to-left associativity. That means f(v) value will be evaluated first, then its result will be added to the current value of v.

So in your example it should be 4, not 3:

C++: (demo)

int f(int& v) {
  v++;
  return 2;
}

int main() {
  int v = 1;
  v += f(v);
  cout << v; // 4
}

Perl: (demo)

sub f {
  $_[0]++;
  return 2;
}

my $v = 1;
$v += f($v);

print $v; # 4
like image 94
raina77ow Avatar answered Oct 26 '22 21:10

raina77ow