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

瘦欲@ 提交于 2021-01-03 07:00:57

问题


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.


回答1:


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.




回答2:


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
}



回答3:


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.




回答4:


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.




回答5:


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;
}



回答6:


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.



来源:https://stackoverflow.com/questions/15815718/how-to-break-a-loop-by-a-shorthand-if-else-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!