int main() {
int x = 0;
int i;
for (i == 0; i < 3; i++) {
x = x * 2;
}
}
This code runs without errors and I’m not sure why. When I initialize the loop counter, I put the equality symbol instead of just the equal sign, yet it still treats i as 0. Why does C not recognize that I made a mistake here?
>Solution :
Your code has undefined-behavior.
It might seem to work well but you cannot rely on that.
i is never initialized in your code and therefore has an indetermined value.
The initialization clause of the loop check i‘s indetermined value against 0 (and the result of the comparison is discarded anyway).
Then the uninitialized i is read for checking if the loop should continue to the next iteration (with i < 3) and finally incremented with i++ (if the former condition will be evaluated to true).
Both of these will invoke undefined-behavior, and therefore no outcome is guaranteed.