Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does C read an equality operator in the initialization of the counter of a "for" loop?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading