How to break a loop by a shorthand "if-else" result?

David von Tamar picture David von Tamar · Apr 4, 2013 · Viewed 7k times · Source

Suppose I have got a shorthand if-else statement inside a loop as in this case :

for(...)
{
    a = b == c ? b : c;
    // More unnecessary code if the result was true.
}

And I would like to break the loop by the result of the condition:

for(...)
{
    a = b == c ? b break : c;
    // Now the unnecessary code is not executed.
}

I realize I could just type it in a full way as in this example:

for(...)
{
    if( b == c )
    {
        a = b;
        break;
    }
    else
    {
        a = c;
    }
    // Now the unnecessary code is not executed.
}

But it is too long and I am trying to have every breaking condition in a single line since there are several of them.

Answer

itsme86 picture itsme86 · Apr 4, 2013

You can use a shortened syntax without utilizing the ternary operator, but what you're trying to do isn't possible. You also don't need an else if you have a break statement in the if.

for (...)
{
    if (b == c) { a = b; break; }

    a = c;
    // More code if b does not equal c
}