C++ 逗号运算符的优先级
Precedence of the C++ 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;
}
我目前正在学习运算符优先级。知道逗号运算符在 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
但是代码的计算顺序改为:
sum += val;
++val;
为什么逗号运算符似乎影响了计算顺序?
这与优先级无关;这是关于评估的顺序。与大多数其他 C++ 运算符(C++17 之前)不同,逗号运算符 strictly 强制执行特定的评估顺序。逗号表达式始终从左到右求值。
嗨,我对以下代码有点困惑:
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;
}
我目前正在学习运算符优先级。知道逗号运算符在 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
但是代码的计算顺序改为:
sum += val;
++val;
为什么逗号运算符似乎影响了计算顺序?
这与优先级无关;这是关于评估的顺序。与大多数其他 C++ 运算符(C++17 之前)不同,逗号运算符 strictly 强制执行特定的评估顺序。逗号表达式始终从左到右求值。