【问题标题】:Compound assignment operators, what happens if the value is modified (in the meanwhile)?复合赋值运算符,如果值被修改(同时)会发生什么?
【发布时间】:2013-06-04 21:32:49
【问题描述】:

考虑以下伪代码(与语言无关):

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

   return 2;
}

int v = 1;

v += f(v);

当函数f在评估v += f(v)时改变y(即v),是v的原始值“冻结”并变为v“丢失”?

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

【问题讨论】:

    标签: language-agnostic programming-languages operators pseudocode compound-assignment


    【解决方案1】:

    在大多数语言中,+= 运算符(以及任何其他复合赋值运算符,以及简单赋值运算符)具有从右到左的关联性。这意味着将首先评估f(v) 的值,然后其结果将被添加到v当前值。

    所以在你的例子中应该是 4,而不是 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
    

    【讨论】:

    • 也就是把v的值加右边的量一样吧?
    • 我会说'评估右侧,然后将 v 增加其结果'。这里的重点是评估的顺序。
    • 好,明白了。感谢您的回答和活生生的例子。
    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多