相关疑难解决方法(0)

逗号运算符的正确用法是什么?

我看到了这段代码:

if (cond) {
    perror("an error occurred"), exit(1);
}
Run Code Online (Sandbox Code Playgroud)

为什么要这么做?为什么不呢:

if (cond) {
    perror("an error occurred");
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)

c c++ coding-style comma-operator

37
推荐指数
5
解决办法
4064
查看次数

在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
查看次数

我们在条件三元运算符中使用逗号时发现的东西?

好吧,我在三元运算符中有一个关于逗号的问题.剪掉垃圾,代码如下:

void test_comma_in_condition(void)
{
    int ia, ib, ic;

    ia = ib = ic = 0;
    bool condition=true;

    cout<<"Original:"<<endl;
    cout<<"ia: "<<ia<<endl;
    cout<<"ib: "<<ib<<endl;
    condition?(ia=1, ib=2):(ia=11, ib=12);
    cout<<"After:"<<endl;
    cout<<"ia: "<<ia<<endl;
    cout<<"ib: "<<ib<<endl;

    ia = ib = ic = 0;
    condition?ia=1, ib=2, ic=3:ib=22,ia=21, ic=23;
    cout<<"The operation must be bracketed, or you'll see..."<<endl;
    cout<<"ia: "<<ia<<endl;
    cout<<"ib: "<<ib<<endl;
    cout<<"ic: "<<ic<<endl;

    condition?ia=1, ib=2, ic=3:ia=21, ib=22, ic=23;
    cout<<"The operation must be bracketed, or you'll see..."<<endl;
    cout<<"ia: "<<ia<<endl;
    cout<<"ib: "<<ib<<endl;
    cout<<"ic: "<<ic<<endl; 

    return;
}
Run Code Online (Sandbox Code Playgroud)

输出将如下:

Original:
ia: 0 …
Run Code Online (Sandbox Code Playgroud)

c++ ternary

1
推荐指数
2
解决办法
1929
查看次数