Hi,
Hope the stated 2 snippets are logically same.
But I am getting error for the second code snippet.

Generally the ternary operator statement is similar to a if else statement.

regarding the second code snippet, where by the continue keyword is used in the ternary opertor statement. It throws the C2059 error.

Why so ?
Please correct me if I am wrong.
Comments and guidance are welcome.

Thanks & Regards,
malini.k

code  snippet 1

Int I =0;
While ( i<7)
{
     I++;
     If (I %2 == 0)
     {
                Continue;
     }
     else
    {
              Cout << I << endl;
    }
}
 
Output: 1 3 5 7.


code snippet 2

int i = 0;

While ( I < 7)
{
  I ++;
  (I %2 == 0) ? continue : cout << i<< endl;
}

Recommended Answers

All 2 Replies

Mis-using the ternary operator is bad coding practice; the : and ? should be logically similar, for it to be a reasonable thing to do. How about this:

if (i%2 == 0)
    continue;
  cout << i << endl;

There does not need to be an else or ? after a continue, break, or return.
Putting each statement on a separate line makes it easy to single-step through the code in the debugger.

Hi Lew,

Thanks for the comments and suggestion.

Regards,
malini.k

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.