嗨,我有点搞不懂下面的代码:
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;为什么逗号操作符似乎影响了评估的顺序?
发布于 2019-12-11 16:38:23
这与优先级无关,而是关于评估的顺序。逗号运算符与大多数其他C++运算符(pre++17)不同,它严格执行特定的求值顺序。逗号表达式总是从左到右计算.
https://stackoverflow.com/questions/59290239
复制相似问题