-2

I noticed a strange behavior of a for cycle...

Case 1:

Let us have an internal initialization of i variable

for ( int i=10; i <=10; i++)
{
    std::cout << i;
}
return 0;

Output:

10

Case 2:

Now we initialize i outside the cycle

int i = 10;

for ( ; i <=10; i++)
{
    std::cout << i;
}
return 0;

Output:

Nothing will be print

Case 3:

Initialization any variable not related to i:

int i = 10;

for ( int k = 0 ; i <=10; i++)
{
    std::cout << i;
}
return 0;

Output:

10

Question

How can depend a result of a cycle condition on the place where we initialize variable i?

Updated results

I traced a code using degugger and VS 2010 really jumps over a cycle in case 2. However g++ works well. Maybe a bug in compiler?

Fianal results After reboot it works correcly. Something between heaven and earth. Sorry for the useless question....

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
justik
  • 4,145
  • 6
  • 32
  • 53

2 Answers2

0

If case 2 doesn't print 10 you have a bug in your compiler or the output isn't being flushed. Add a << "\n" to the output as well.

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • 2
    Actually, just adding `'\n'` doesn't flush the output, as I discovered in [this question](http://stackoverflow.com/q/8311058/440558). However, the program terminating should _definitely_ flush the output. – Some programmer dude Aug 17 '12 at 10:48
  • But If it flushes when `i` is initilized at loop and it doesn't flush when i is initilized before loop is also a bug in compiler. But I don't think VS will do that. – Neel Basu Aug 17 '12 at 10:52
  • @ Andreas it looks like a VS 2010 compiler bug, g++ works well – justik Aug 17 '12 at 10:53
  • I would be very surprised if this was a VS 2010 compiler bug, it's not like you're at the frontier of C++ features :) – Andreas Brinck Aug 17 '12 at 11:02
  • 1
    @justik VS2010 works as expected on my windows 7 x64 machine. – WiSaGaN Aug 17 '12 at 11:10
0

The second one prints 10 too. If it doesn't there is a bug in your compiler or you are using a wrong compiler.

I've run the same code in http://ideone.com/UB0V0. you can have a see it it. it prints 10

Neel Basu
  • 12,638
  • 12
  • 82
  • 146