三元运算符,如果我避免写"expression 2",它会起作用,但是如果我不写"expression 3",则会出现错误 [英] Ternary operator, if I avoid writing ' expression 2 ' it works but if I not write 'expression 3 ' it gives an error

查看:104
本文介绍了三元运算符,如果我避免写"expression 2",它会起作用,但是如果我不写"expression 3",则会出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

#include<iostream>

int main()
{
    int a=4,b,c;
    a==3 ? : b=a*a ;     // Works fine
    a==4 ? c=a*a : ;     // ERROR Expected Primary expression before ;
}

  • 第一个条件语句

    我没有写'表达式2 ',但是不会产生错误

    I did not write 'Expression 2' but it will not produce error

    第二个条件语句

    我没有写'表达式3 ',它给出了错误

    I did not write 'Expression 3' it gives an error

    那么为什么在' Expression 2 '和' Expression 3 '中有所区别?

    so why it is differentiating in 'Expression 2' and 'Expression 3' ?

    推荐答案

    这在GNU C/C ++中受支持,称为

    This is supported in GNU C/C++ and is called the Elvis operator. It's not allowed in standard C++ (e.g. MSVC++ doesn't support it).

    官方文档

    6.8省略操作数的条件条件表达式中的中间操作数可以省略.然后,如果第一个操作数不为零,则其值为条件表达式的值.

    6.8 Conditionals with Omitted Operands The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.

    因此,表达式

    x?:y

    具有x的值(如果它不为零);否则,y的值.

    has the value of x if that is nonzero; otherwise, the value of y.

    此示例完全等同于

    x?x:y

    在这种简单情况下,省略中间操作数的功能不是特别有用.当第一个操作数确实有用或可能(如果它是宏参数)可能包含副作用时,它才变得有用.然后在中间重复操作数将产生两次副作用.省略中间操作数将使用已经计算出的值,而不会导致重新计算它的不良后果.

    In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

    这篇关于三元运算符,如果我避免写"expression 2",它会起作用,但是如果我不写"expression 3",则会出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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