3

Why is the following line producing errors?

for(int i = 0, int pos = 0, int next_pos = 0; i < 3; i++, pos = next_pos + 1) {
  // …
}

error: expected unqualified-id before ‘int’
error: ‘pos’ was not declared in this scope
error: ‘next_pos’ was not declared in this scope

Compiler is g++.

apaderno
  • 28,547
  • 16
  • 75
  • 90
Variance
  • 873
  • 2
  • 10
  • 10
  • 3
    Related: http://stackoverflow.com/questions/3337126/in-c-why-cant-i-write-a-for-loop-like-this-for-int-i-1-double-i2-0 which seems to reference an earlier http://stackoverflow.com/questions/2340073/multiple-counter-problem-in-for-loop which appears to be pretty good duplicate for *this* question. – dmckee --- ex-moderator kitten Aug 01 '10 at 22:50

2 Answers2

15

You can have only one type of declaration per statement, so you only need one int:

for(int i = 0, pos = 0, next_pos = 0; i < 3; i++, pos = next_pos + 1)
siride
  • 200,666
  • 4
  • 41
  • 62
  • 2
    And it's disappointing that there's no means to make some of the declarations `const` and some of them not. – seh Aug 01 '10 at 22:38
  • 16
    @seh: `for ( struct { int anything; const int you; float want;} data = {5, 10, 3.14f}; ...; ...)` – GManNickG Aug 01 '10 at 22:52
  • 1
    @seh @strager: :) I agree it's a bit ugly, I probably wouldn't do it in real code (haven't so far), but it is a way. Far easier just to define the variables above the loop. – GManNickG Aug 02 '10 at 02:46
4

In a normal program:

int main()
{

int a=0,int b=0,int c=0;
return 0;    

}

will never work and is not accepted.

This is what you are actually trying to do inside the for loop!

Vijay
  • 65,327
  • 90
  • 227
  • 319