为什么break不能与三元运算符一起使用? [英] Why break cannot be used with ternary operator?

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

问题描述

while(*p!='\0' && *q!='\0')
{
        if(*p==*q)
        {
               p++;
               q++;
               c++;
        }
        else
        break;
}

我已经使用三元运算符编写了此代码,但为什么它给break语句带来错误?

I have written this using ternary operator but why its giving error for break statement?

*p==*q?p++,q++,c++:break;

gcc编译器给出此错误:'break'之前的预期表达式

gcc compiler gives this error: expected expression before ‘break’

推荐答案

使用三元运算符时,它不像 if 。三元运算符的格式为:

When you use a ternary operator, it is not like an if. The ternary operator has this form:

(condition ? expression_if_true : expression_if_false);

这两个表达式必须具有相同的类型,否则就很无聊了。

Those two expression must have the same type, otherwise that makes nonsense.

正如Thilo所说,您不能在此运算符中使用语句,只能使用表达式。这是因为取决于条件,整个三元运算符本身必须是表达式。

And as Thilo said, you cannot use statement in this operator, only expression. This is because the whole ternary operator must be an expression itself, depending on the condition.

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

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