2

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?

Himanshu Aggarwal
  • 1,803
  • 2
  • 24
  • 36
  • Seems like a bug in Turbo C to me. – Barmar Sep 21 '13 at 15:57
  • 1
    This is bug in Turbo C compiler since last 10 year. (I noticed it 10 year back) additionally as I remember if you use `i = 0` and write for loop as `for(; i;) ` it will behave correctly Give it a try!! – Grijesh Chauhan Sep 21 '13 at 18:12
  • yep it works perfectly fine @GrijeshChauhan. – Himanshu Aggarwal Sep 21 '13 at 21:01
  • @HimanshuAggarwal Don't use Turbo, better to use GCC in Linux when you ae learner. – Grijesh Chauhan Sep 22 '13 at 04:29
  • One thing to be noted is that if it is true first time why it is false second time? @HimanshuAggarwal – A.s. Bhullar Sep 24 '13 at 15:42
  • @A.s.Bhullar that is the reason why i posted this question here. I got too confused with this behavior. – Himanshu Aggarwal Sep 25 '13 at 02:13
  • May it is bug or may be not. Is there any difference between constant 0 and variable 0 i.e(i=0)? I have tried it with NULL and constant expression that results 0(2-2) it behave similarly. I have one more issue when we replace 0 with i(where i=0)then its Rvalue is used(according to me I m not sure),but when we use constant, What happen I dont know. May these issues are behind this problem. – A.s. Bhullar Sep 25 '13 at 05:14

2 Answers2

1

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.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
1

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