Ansh Srivastava
Ansh Srivastava

Reputation: 19

Is continue(keyword) not allowed inside the ternary operator in c++?

Below is the code:-

 #include<iostream>
 using namespace std;
 int main(){
   int n, c1=0, ans=0;
   cin>>n;
   string s;
   cin>>s;
   for(int i=0; i<n; i++){//string always start with 0
     s.at(i)!='D'?++c1:--c1;//statement 1
     (c1!=0 && s.at(i)!='U')?continue:ans++;//statement 2

  }
  cout<<ans<<endl;
}

statement 2 prompts an error:-

  solution.cc: In function ‘int main()’:
  solution.cc:10:33: error: expected primary-expression before ‘continue’
     (c1!=0 && s.at(i)!='U')?continue:ans++;
                             ^~~~~~~~
  solution.cc:10:33: error: expected ‘:’ before ‘continue’
  solution.cc:10:33: error: expected primary-expression before ‘continue’

But when I changed statement 2 a bit, then it prompts no error !

for(int i=0; i<n; i++){//string always start with 0
    s.at(i)!='D'?++c1:--c1;
    if(c1==0 && s.at(i)=='U')//statement 2
         ans++;      

Does it reveals that continue or any other keyword are not allowed inside ternary syntax? Will be much obliged for the answer.

Upvotes: 0

Views: 194

Answers (2)

P.W
P.W

Reputation: 26800

  1. The ternary conditional expressions have the form

    E1 ? E2 : E3

    Where E1, E2 and E3 must be expressions.

  2. On the other hand, continue is a statement.

    The continue statement causes a jump, as if by goto to the end of the loop body (it may only appear within the loop body of for, range-for, while, and do-while loops).

Taken together it would mean that continue cannot appear in a ternary conditional even if the conditional is part of one of the loops mentioned above.

Upvotes: 1

No, it's not. continue is a statement and only expressions are allowed inside ternary operators.

Upvotes: 3

Related Questions