I am using Visual C++ 2005 with SP1

why does the following code generate a compiler error (error C2062: type 'int' unexpected)?

for(int i=0,int j=0;i<5;i++,j++){}

Note the following two variations generate no compile error

int i,j;
for(i=0,j=0;i<5;i++,j++){}
int j;
for(int i=0,j=0;i<5;i++,j++){}

Is this just a bug in the Visual C++ compiler or is this the way the standard is defined?

Thanks.

You can only specify one type of loop counter.

>>Is this just a bug in the Visual C++ compiler
Not a bug. That type a statement is never allowed

int a, int b; // error
int a,b; // ok

OK thanks. All these years of programming and I never knew i++,j++; was a valid C++ line of code. I would always just write two lines of code. I thought it was just a special case in the header of a for loop and assumed the int i=0, int j=0 would work the same way. Interestingly, a google search for "for(int i=0,int j=0" will give some hits, one of which is from books.google.com Do some compilers support this? It would be nice because then I could do the following:

for(int i=0, double d=1;i<5;i++,d*=1.5){cout<<"1.5^"<<i<<"="<<d<<endl;}

This would make for cleaner code as it is clear that i and d are used only inside the for loop.

The for statement syntax:

for (for-init-statement condition(opt); expression)
for-init-statement::
    expression-statement
    simple-declaration
expression-statement::
    expression(opt) ;

Informally simple-declaration is well-known type names-with-possible-initializators construct. The semicolon token terminates construct in C++.

Obviously, int i = 0, int j = 0; and especially int i = 0, double d = 1; are not valid C++ declarations.

About i++, j++ - that's another matter. It's an expression with comma operator (evaluate left part and discard its result then evaluate right part - it's an expression result).

It would be nice because then I could do the following:

for(int i=0, double d=1;i<5;i++,d*=1.5){cout<<"1.5^"<<i<<"="<<d<<endl;}

This would make for cleaner code as it is clear that i and d are used only inside the for loop.

I disagree. That to me is confusing and unclean.

On the other hand:

for (int i = 0; i < 5; i++)
{
    double d = 1;
    cout << "1.5^" << i << "=" << d << endl;
    d *= 1.5;
}

This is much easier to read because
1) i is the only variable important to the for statement itself
2) d is defined to be used only in the loop
3) formatting and whitespace makes the code much easier to read

Regrettably, it does not work (d is local auto var in the loop body block):

for (int i = 0; i < 5; i++)
{
    double d = 1; // new incarnations for 0, 1, 2, 3, 4...
    cout << "1.5^" << i << "=" << d << endl;
    d *= 1.5;
}

Right solution:

double d = 1.0;
for (int i = 0; i < 5; ++i, d*=1.5)
{
    cout << "1.5^" << i << "=" << d << endl;
}
This article has been dead for over six months. Start a new discussion instead.