为什么break不能与三元运算符一起使用?

时间:2016-06-16 09:36:45

标签: c break ternary

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

我用三元运算符编写了这个,但为什么它给break语句提供错误?

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

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

2 个答案:

答案 0 :(得分:7)

使用三元运算符时,它不像<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.6.201602180812</version> <configuration> <exclude> <exclude>LOMBOK.DATA</exclude> </excludes> </configuration> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <goals> <goal>report</goal> </goals> <phase>prepare-package</phase> </execution> </executions> </plugin> 。三元运算符具有以下形式:

if

这两个表达式必须具有相同的类型,否则会产生废话。

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

答案 1 :(得分:2)

语法为:

(condition ? expr_true : expr_false);

expr_true expr_false 必须具有公共类型(这将是三元运算符的结果)。 当然,break也不是表达式,而是一种陈述。

相关问题