相关疑难解决方法(0)

逗号运算符如何工作

逗号运算符如何在C++中工作?

例如,如果我这样做:

a = b, c;  
Run Code Online (Sandbox Code Playgroud)

最终是否等于b或c?

(是的,我知道这很容易测试 - 只是在这里记录,以便有人快速找到答案.)

更新: 此问题在使用逗号运算符时暴露了细微差别.只是记录下来:

a = b, c;    // a is set to the value of b!

a = (b, c);  // a is set to the value of c!
Run Code Online (Sandbox Code Playgroud)

这个问题实际上是受到代码中的拼写错误的启发.打算做什么

a = b;
c = d;
Run Code Online (Sandbox Code Playgroud)

转换成

a = b,    //  <-  Note comma typo!
c = d;
Run Code Online (Sandbox Code Playgroud)

c++ comma-operator

165
推荐指数
6
解决办法
5万
查看次数

在C++中,条件运算符中逗号运算符的优先级是什么?

这里发生了什么事?

#include <iostream>
using namespace std;

int main(){

    int x=0,y=0;
    true? ++x, ++y : --x, --y; 
    cout << "x: " << x << endl;
    cout << "y: " << y << endl; //why does y=0 here?

    x=0,y=0;
    false ? ++x, ++y : --x, --y; 
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
}

x: 1
y: 0

x: -1
y: -1
Run Code Online (Sandbox Code Playgroud)

第二种情况似乎很好.我希望x和y在第一种情况下增加到1,但只有左手操作数增加.

c++ comma operator-precedence

10
推荐指数
1
解决办法
1308
查看次数

标签 统计

c++ ×2

comma ×1

comma-operator ×1

operator-precedence ×1