Home > database >  count>=10? break : continue;
count>=10? break : continue;

Time:01-29

count>=10? break : continue;

Why does this statement give errors ? Any help will be highly appreciated.

58 16 [Error] expected expression before 'break'

This error occurs.

CodePudding user response:

Why does this statement give errors ?

?: is not a "short version of if" as it is incorrectly described on many sites.
?: is not a statement, it is an operator.

An operator joins one, two or three operands to produce an expression. An expression is a piece of code that is computed and produces a value. A statement is a piece of code that does something. They are different things.

A statement can contain expressions. An expression cannot contain statements.

break and continue are statements. This is why the fragment count >= 10 ? break : continue; is not a valid statement and does not compile.

Use an if statement and it works:

if (count >= 10) {
  break;
} else {
  continue;
}

CodePudding user response:

I think instead of using ternary operator use if else.

CodePudding user response:

As it follows from the error message

58 16 [Error] expected expression before 'break'

in this statement with the conditional operator

count>=10? break : continue;

the compiler expects expressions instead the statements break and continue.

According to the C Standard the conditional operator is defined the following way

logical-OR-expression ? expression : conditional-expression

As you can see it includes three expressions.

Instead of using the conditional operator you could use the if-else statement the following way

if ( count>=10 )
{ 
    break;
}
else
{ 
    continue;
}

But in any case this construction with break and continue statements looks badly.

It seems you should move the condition count>=10 in the loop statement that is used. Or it will be enough to write

if ( count>=10 )
{ 
    break;
}

without the else part of the if statement.

  • Related