goto无法使用?:C中的运算符 [英] goto not working with ?: operator in C
问题描述
出于学习目的,我编写了以下代码段:
For learning purposes, I wrote the following code snippet:
for(int i=0;i<10;i++)
{
for(int j = 0;j<5;j++)
{
//(i==j && i==3)? (goto found) : printf("stya here\n");
if(i==j && i==3){goto found;} else {printf("stay here\n");}
}
}
found:
printf("yes I am here");
但是我想知道当我发现内部循环中被省略的语句没有给出错误时,现在我很困惑关于if-else并不总是可以用?:
运算符替换。这是什么事实?为什么注释的语句会给出错误?
But I wondered when I discovered the omitted statement inside the inner loop not gives error and now I am confused about if-else is not always replaceable with ?:
operator. What is the fact here? Why does the commented statement give an error?
推荐答案
?:
运算符不能代替 if
。它仅适用于以下表达式: condition? expr1:expr2
,其中两个子表达式 expr1
和 expr2
属于同一类型(然后整个表达式是同一类型。
The ?:
operator is not replacement for if
. It works only for expressions: condition ? expr1 : expr2
where both sub-expressions expr1
and expr2
are of the same type (and the whole expression then is of the same type).
goto
不是表达式,它是一个语句。
goto
is not expression, it is a statement.
这篇关于goto无法使用?:C中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!