cconditional-operatorvariable-initialization

C - ternary operator in initialization statement of a for-loop


I am quite new to C and preparing for a test by working through some sample questions. Given the code below, I don't understand the initialization of int j by using the ternary operator.

for (int j = i ? foo : 2; j < 10; j++)
#include <stdio.h>
int main (void) {

    int foo = -1;
    do {
        int i = foo++;

        if (foo > 8)
            break;
        else if (foo < 5)
            continue;
        for (int j = i ? foo : 2; j < 10; j++) {
            printf("foo=%d, i=%d, j=%d;", foo, i, j);
        }
        i = foo++;
    } while (1);
    return foo;

    return 0;
}

The results I got from debugging:

So my questions would be:


Solution

  • How does this "ternary initialization work"?

    j is being initialized with the value of the expression i ? foo : 2. Since i has a non-zero value (4), the second part of the ternary is evaluated, i.e. foo which is 5, and that value is what j is initialized with.

    Why is int j = 0 without being initialized before? Shouldn't it be some random numbers?

    0 is a random number. There's no particular reason it had to be this value.