为什么三元运算符不支持块? [英] Why ternary operator does not support blocks?

查看:96
本文介绍了为什么三元运算符不支持块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么三元运算符没有块?换句话说,为什么以下代码不起作用并报告{}大括号错误?

Why the ternary operator does not have blocks? In other words, why the following code does not work and reports error for {} braces?

int main()
{
    int i = 1;
    (i==1)?{printf("Hello\n")}:{printf("World\n")};
    return 0;
}

编辑

也许这个问题被误解了.那是:为什么不支持块?为什么只用单个表达式?

Perhaps the question is misunderstood. It was: why blocks are not supported? Why only single expression?

为什么不允许这样做?

Why this is not allowed to work?

int main()
{
    int i = 1;
    (i==1)?{printf("Hello\n");printf("World\n");}:{printf("Bye\n");printf("World\n");};
    return 0;
}

一个原因可能是三元数通常用于左侧的条件赋值,并且块将没有这样的返回值,否则会与块中的多个语句混淆.

One reason could be that ternary are often used for conditional assignment on left side and blocks will have no such returns or it will get confusing with multiple statements inside block.

推荐答案

要引用C11标准第6.5.15章,条件运算符的语法为

To quote C11 standard, chapter §6.5.15, the syntax of the conditional operator is

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

第二和第三操作数是expression,而不是语句.

Where, the second and third operands are expression, not statements.

只需要详细说明,

第二个和第三个操作数应满足以下条件之一:
—两个操作数都具有算术类型;
—两个操作数具有相同的结构或联合类型;
—两个操作数都具有void类型;
—两个操作数都是指向兼容类型的合格或不合格版本的指针;
—一个操作数是一个指针,另一个是空指针常量;或
—一个操作数是指向对象类型的指针,而另一个是指向限定或 不合格版本的void.

One of the following shall hold for the second and third operands:
— both operands have arithmetic type;
— both operands have the same structure or union type;
— both operands have void type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer and the other is a null pointer constant; or
— one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void.



回答问题

为什么只有单个表达式?

再次

引用标准

again, quoting the standard,

....结果是第二个或第三个操作数的值(以所评估的为准),转换为下面描述的类型.

....the result is the value of the second or third operand (whichever is evaluated), converted to the type described below.

语句块,不会给出. expression罐的评估.

Block of statements, will not give a value. The evaluation of an expression can.

这篇关于为什么三元运算符不支持块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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