Search code examples
cfor-loopconditional-operator

How to use ? question mark in for loop in C?


If i is even, for(int j = 0; j < m; j++)

Else if iis odd, for(int j = m-1; j > 0; j--)

I would like to combine the two conditions as follows.

for( (i%2==0) ? (int j = 0; j < m; j++) : (int j = m-1; j > 0; j--))

But it seems to fail.

Is there any way to combine the two conditions using ? or another way in the C language?


Solution

  • You could do something a little hacky and obfuscated, like the following, but I wouldn't recommend it. This counts down from m-1 to 0 if i is odd and counts up from 0 to m-1 if i is even. Note that the original question counts down from m-1 to 1, and I assumed you wanted from m-1 to 0, so correct as needed.

    Be careful with 'unexpected' input values of m, e.g. negatives, because the loop may not terminate when you want in that case.

    #include <stdio.h>
    
    int main()
    {
        int i = 1;
        int m = 8;
        
        int start = i%2 ? m-1 : 0;
        int end = i%2 ? -1 : m;
        int delta = i%2 ? -1 : 1;
        
        for (int j = start; j != end; j += delta)
        {
            printf("j=%d\n", j);
        }
    
        return 0;
    }