Question

I know this is a stupid question to ask but i am just asking this out of my curiosity. I just read this code somewhere:

#include<stdio.h>
int main() {
    for ( ; 0 ; )
        printf("This code will be executed one time.");
    return 0;
}

Output:

This code will be executed one time.

This loop is executing once in Turbo C compiler while not working in gcc, but how can this be possible that this loop execute even for once?

Can you please guide me for the unusual behavior of this code in the Turbo C compiler, if there is any?

Was it helpful?

Solution

It's a bug in the compiler. The C99 standard describes for loops like this:

The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression 
that is evaluated before each execution of the loop body. 
The expression expression-3 is evaluated as a void expression after each 
execution of the loop body. [...]

Given that expression-2 evaluates to false, the code should print no output.

OTHER TIPS

TurboC does not follow the C99 standard. This could explain the unusual behaviour.REst assured, gcc will give you the correct output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top