Вопрос

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.

Это было полезно?

Решение 2

Here is some information on the ternary operator and it's uses: ?: Operator (C#)

What you want to do is just impossible... it's not how it works.

Другие советы

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
}

For the example you've given, you could restructure it so

for (int i = 0; i < count && b != c; ++i)
{
    if( b != c )
    {
        // code
    }
}
a = b;

However, the specific thing you are trying to do (break from within a ternary) is not possible.

The ternary operator (that "shorthand if-else") is only intended to evaluate one of two statements based on the boolean. It's not so much a flow-control construct like if; it actually returns the result of the statement it executes. You can't use it to execute code like that.

If you're ending up with a long else-if-else-if chain, consider refactoring a little. It may be possible to replace it with a switch block.

Make a function for the test. If it's reused, its at least shorter than your example.

int a;
if(TryEqual(b, c, out a))
    break;

bool TryEqual(int x, int y, out res)
{
    if(x == y)
    {
        res = x;
        return true;
    }
    res = y;
    return false;
}

I came up with this solution.

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

Of course the astute reader will notice that you could always assign a=c and then break if and only if b==c as that would be equivalent.

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

That is about is as short and elegant as it is going to get while still keeping those pesky if-else constructs coalesced to a single lines.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top