Search code examples
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:

  • During cycle 6 of the do-while loop, the for loop will be entered for the first time. At this time the values are: i=4, foo=5 and j=0 (according to the debugger, although it was never initialized with the value 0?)
  • When stepping over j changes from 0 to 5 (=foo) - and this change, I don't understand.

So my questions would be:

  • How does this "ternary initialization work"?
  • Why is int j = 0 without being initialized before? Shouldn't it be some random numbers?

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.