Is it possible to fit in a ternary operator as the termination in a for loop?

偶尔善良 提交于 2019-12-08 14:07:03

问题


So, I just want to know if its possible to slip in any code or a ternary operator inside the termination bit of a for loop. If it is possible, could you provide an example of a ternary operator in a for loop? Thanks!

for (initialization; termination; increment) {
   statement(s)
}

回答1:


The termination clause in the for statement (if supplied - it's actually optional) can be any expression you want so long as it evaluates to a boolean.

It must be an expression, not an arbitrary code block.




回答2:


Yes you can since only thing here is termination should be a boolean

for (int i=0; i==10?i<5:i<6; i++) {


}

But what is the point of this?

Things to remember. Termination condition of a for loop should be a boolean




回答3:


Absolutely, it is possible:

for (int i = 0 ; i < someCondition ? first : second ; i++) {
    ...
}

you can use ternary operators or any expressions in all three parts of the loop header:

for (int i = flag ? a : -a ; i != (flag ? 2*b : -2*b) ; i += flag ? 1 : -1 ) {
    ...
}

If you need to insert more complex logic into the termination condition, a good approach would be to define a method: it usually improves readability of your loop:

boolean checkCondition(int i) {
    ...
}

...

for (int i = 0 ; checkCondition(i) ; i++) {
    ...
}



回答4:


The termination part of the for loop requires a boolean condition. You can pass anything that gives a boolean value for the termination part.

For ex:

for (int i = 0; i<5?true:false; i++) 
{

}


来源:https://stackoverflow.com/questions/26158515/is-it-possible-to-fit-in-a-ternary-operator-as-the-termination-in-a-for-loop

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