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");
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?
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
is not expression, it is a statement.