Confusing for… while loop syntax in C

I accidentally noticed that the following snipped of code compiles under GCC:

void myFunction(void) {
    int i, y = 0;
    for (i = 0; i < 10; i++)
        y++;
    while (y);
}

I’ve never encountered such a piece of code before and wasn’t able to find any information about such a construct after doing some searching around. It leads me to wonder what the purpose of such a construct is and what it is meant to do?

>Solution :

There is no such thing as a for ... while loop.

What you see are two independent loops.

First, there is a for loop. The only instruction in the body of that loop is y++;.

Then you see anoter loop: while(y) ;. That is not related at all to the for loop. The body only consists of an empty instruction ;. As y never changes in the body, that will be an infinite loop.

Leave a Reply