JScriptChan wrote on Apr 19th, 2009, 10:38pm:Hello friends,I suddenly come across an once neglected problem:
If you define a variable in sequence like below
int a=1;
int a=2;
then the error message saying "duplicate" will appear.
But when I write in this way,say,in a loop:
for(int i=0;i<2;i++)
{
int g=1;//here no duplicate
println(g);
//i+=1;
}
It works.It seems that g is defined the same way as in the former example,but no duplicate error pop up.What's the reason?Any advice is appreciated,thank you in advance.
The compiler checks syntax, if it were to actually run the code, you may get the duplicate error, but because it is inside the for loop, the syntax looks correct to the compiler (ie. the compiler doesn't run the loop). However, as mentioned, the value of g will be 1 and not available outside the for loop. So if you were to use it outside the loop,
for(int i=0;i<2;i++)
{
int g=1;//here no duplicate
println(g);
//i+=1;
}
if(g)
{}
you will get a compile error, so to prevent that error you will need to declare it outside the loop,
int g;
for(int i=0;i<2;i++)
{
int g=1;//here no duplicate
println(g);
//i+=1;
}
if(g)
{}
Now you will get your duplicate error, and to correct it,
EditDepending on the compiler, you may not get the duplicate error as the int g outside the loop will be a different variable than that inside the loop, but this is good for visualizationint g;
for(int i=0;i<2;i++)
{
g=1;
println(g);
//i+=1;
}
if(g)
{}