If I write:
int a = 1;
int a = 2;
I get a compile time error, however if I write:
while(1) {
int a = 1;
}
no compile time error - whats the difference? does the while loop have its own scope or something?
If I write:
int a = 1;
int a = 2;
I get a compile time error, however if I write:
while(1) {
int a = 1;
}
no compile time error - whats the difference? does the while loop have its own scope or something?
In the second case, you don't define multiple variables with the same name in the same scope. What happens is this
while(1) { //there is no variable a in this scope
int a = 1; //define a variable a at this point.
} //variable a is no more
In the first case, however, we have
int a = 1; //define variable a;
int a = 1; //variable a has been defined in this scope already, so error!
The difference is in the scope. The scope is determined by the curly braces - {}. In the first case both variables share the same scope - that's why you have received an error. In the second case you define local (for the scope of while) variable. A new variable is created on each iteration of the loop. This is perfectly valid and that's why you don't get error. If this is unclear to you I'd suggest researching it more, here is a good start - http://crasseux.com/books/ctutorial/Scope.html
After you do int a = 1;, you leave a { } block, removing every variables declared in that block. As you are doing a while (true) loop, you will enter another { } block but that new block will not be 'aware' that you previously created an 'a' variable... because it was swept away !
For example:
{
int a = 1;
}
a = 2;
will not compile for the same reason
Edit: that's crazy, within a minute there was already five answers !