Is it possible to fit in a ternary operator as the

2019-06-14 16:09发布

问题:

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++) 
{

}