-1

A similar question has been answered here[https://stackoverflow.com/a/13421435/3276830 ]. The author says

The following code

 for (i=0;i<5;i++);
 {
     printf("hello\n");
 }

is interpreted as follows:

  • Repeat five times for (i=0;i<5;i++)
  • ... do nothing (semicolon)
  • Open a new scope for local variables {
  • ... Print "hello"
  • Close the scope }

However, for the following for loop

int i = 0;
for(;i++;cout<<i<<" ");
cout<<i<<" ";

The output I get is just 1, but I expected it to be 123456.....

Edit, I know the difference between prefix and postfix operation. But yeah I did miss that it was 0 the first time loop ran.

Varun Garg
  • 2,464
  • 23
  • 37

2 Answers2

3
int i = 0;
for(;i++;cout<<i<<" ");

This loop can never execute because i is 0, so i++ evaluates to 0 (the value before incrementing it) which is false. Try ++i instead.

1

the

for(;;i++, cout<<i<<" ");

looks more aesthetically :) correct and will work no matter prefix or postfix

StahlRat
  • 1,199
  • 13
  • 25