Arun
Arun

Reputation: 121

Why can't we declare two variable in a for loop?

The below code generates an error when i run it but if i declare at-least one variable outside the loop the code works fine.Why can't i declare both the variables in the loop itself?

Error:

#include<iostream>
#include<conio.h>
using namespace std ;

int main()
{
for(int j=0,int i=0;i<4&&j<2;i++,j++)
{
    cout<<"Hello"<<endl ;
}
getch() ;
return 0 ;
} 

Works Fine:

#include<iostream>
#include<conio.h>
using namespace std ;

int main()
{
int i ;
for(int j=0,i=0;i<4&&j<2;i++,j++)
{
    cout<<"Hello"<<endl ;
}
getch() ;
return 0 ;
} 

Upvotes: 0

Views: 498

Answers (3)

Matt Soucy
Matt Soucy

Reputation: 103

Note that the given answers "only" handles making multiple variables of the same type.

If, for some bizarre reason, you would need to do multiple types, this is valid (though awful):

for(struct {int a; double b} loop = {0, 1.5}; loop.a < loop.b; loop.a++)
{
    // Awful hacks
}

Upvotes: 0

user529758
user529758

Reputation:

Because that's how the Standard defines the syntax. There's nothing "wrong" in particular with the idea, but apparently it was decided that you can only have one declaration in the initialization part.

If you want to declare multiple variables, use a comma to enumerate them (but this way, you can only declare variables of the same type):

for (int i = 0, j = 10; i < 10; i++, j--)

However, I'm not sure you should be doing this. After a certain point, this evolves into an unreadable mess.

Upvotes: 5

ruakh
ruakh

Reputation: 183270

You can, but the notation for declaring two variables in a single declaration is like this:

int j=0, i=0;

with no second int.

(This is actually what your second version is doing; you might think it's assigning the already-declared i, but actually it's declaring a new one, whose scope is the for-loop.)

Upvotes: 8

Related Questions