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
Était-ce utile?

La 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top