Pregunta

How can i select the increment on a for loop depending on a boolean,i am trying to do something like this:

    for (int y = iniY; isdown? (y >= endY): (y <= iniY+dy) ; isdown? --y:y++);

the for loop accepts the termination but not the increment...

The working code i currently have is something like this:

    if(isdown)
        for (int y = iniY; y >= endY; --y) {
            code lines...
        }
    else
        for (int y = iniY; y <= iniY+dy; ++y) {
            code lines...
        }

the code can not be extracted to a new method because it works on many variables...

¿Fue útil?

Solución

Similar to minitech's solution but without a branch inside the loop.

int end = isdown ? iniY - endY : dy;
int direction = isdown ? -1 : +1;

for(int i = 0; i <= end; i++) {
    int y = iniY + direction * i;
    …
}

Otros consejos

for(initialization;condition; increment/decrement){}

If condition part of for loop is failed, then increment part will not work.

I’d do this:

int end = isdown ? iniY - endY : dy;

for(int i = 0; i <= end; i++) {
    int y = isdown ? iniY - i : iniY + i;
    …
}

That is to say, figure out the difference and loop over that. It’s easier to understand.

I'd say that there is a big smell in your code. I'd concentrate on refactoring your code, rather than trying to hack this particular bit to make it work. If the code relies on to many variables to squirt into an extracted method, then something seems wrong in the design.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top