C++ 逗号运算符的优先级

oct*_*pus 5 c++ operator-precedence comma-operator

嗨,我对以下代码有些困惑:

int main()
{
    int sum = 0, val = 1;
    while(val <= 10)
        sum += val, ++val;     //source of problem

    cout<<"Sum of 1 to 10 inclusive is " << sum << endl;
    //
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我目前正在学习运算符优先级。知道逗号运算符在 C++ 运算符中的优先级最低,我希望 while 循环中的语句按以下顺序计算:

++val; //so that val is incremented to 2 the first time the code in the while loop is evaluated
sum += val; //so that the incremented value of val is added to the sum variable 
Run Code Online (Sandbox Code Playgroud)

但代码按此顺序评估:

sum += val;
++val;
Run Code Online (Sandbox Code Playgroud)

为什么逗号运算符似乎影响了评估顺序?

Nic*_*las 13

这与优先级无关;这是关于评估的顺序。与大多数其他 C++ 运算符(C++17 之前的)不同,逗号运算符严格执行特定的求值顺序。逗号表达式总是从左到右计算。

  • @Raj因为那不是逗号运算符。:) (9认同)
  • @Raj 不是真的。该代码具有未定义(C++17 之前)或未指定(C++17 以来)的行为。不要写这样的代码。您认为为什么要编写这样的代码? (3认同)