Question

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
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top