在条件三元运算符中使用逗号时发现了什么? [英] Something we found when using comma in condition ternary operator?

查看:598
本文介绍了在条件三元运算符中使用逗号时发现了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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;
条件ia = 1,ib = 2,ic = 3:ib = 22,ia = 21,ic = 23;
cout<<操作必须加括号,否则你会看到...<< endl;
cout<<ia:<< ia<< endl;
cout<<ib:<< ib<< endl;
cout<<ic:<< ic<< endl;

条件ia = 1,ib = 2,ic = 3:ia = 21,ib = 22,ic = 23;
cout<<操作必须加括号,否则你会看到...<< endl;
cout<<ia:<< ia<< endl;
cout<<ib:<< ib<< endl;
cout<<ic:<< ic<< endl;

return;
}

输出结果如下:

 原文:
ia:0
ib:0
之后:
ia:1
ib:2
操作必须在括号内,或者你会看到...
ia:21
ib:2
ic:23
操作必须加括号,你会看到...
ia:1
ib:22
ic:23

这是合法吗?

解决方案

这是操作符优先级的问题。您的表达式:

  condition?ia = 1,ib = 2,ic = 3:ib = 22,ia = 21,ic = 23; 

可由编译器理解为:



<$ (ia = 1,ib = 2,ic = 3):( ib = 22)),ia = 21,ic = 23;

此时,您应该能够看到为什么得到程序输出。


Well, I had a question about comma in ternary operator. Cut the crap, the code is below:

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;
}

The output will be like:

Original:
ia: 0
ib: 0
After:
ia: 1
ib: 2
The operation must be bracketed, or you'll see...
ia: 21
ib: 2
ic: 23
The operation must be bracketed, or you'll see...
ia: 1
ib: 22
ic: 23

Is this legal?

解决方案

This is a matter of operator precedence. Your expression:

condition?ia=1, ib=2, ic=3:ib=22,ia=21, ic=23;

is understood by the compiler as:

(condition?(ia=1, ib=2, ic=3):(ib=22)),ia=21, ic=23;

At this point you should be able to see why you get the program output.

这篇关于在条件三元运算符中使用逗号时发现了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆