Reputation: 1037
I am confused as to why I am allowed to do this (the if statement is to just show scope):
int i = 0;
if(true)
{
float i = 1.1;
}
I have a c# background and something like this is not allowed. Basically, the programmer is redeclaring the variable 'i', thus giving 'i' a new meaning. Any insight would be appreciated.
Thanks!
Upvotes: 3
Views: 1038
Reputation: 16650
Turn on "Hidden local variables" in your build settings to get a warning.
Upvotes: 3
Reputation: 9341
You're not redefining i
, so much as shadowing i
. This only works when the i
's are declared at different levels of scope. C# allows shadowing, but not for if
statements / switch
statements, while C/C++/Objective-C allow such shadowing.
After the inner i
goes out of scope, the identifier i
will again refer to the int
version of i
. So it's not changing what the original i
refers to. Shadowing a variable is generally not something you want to do (unless you're careful, shadowing is likely a mistake, especially for beginners).
Upvotes: 1
Reputation: 726499
In C (and by extension, in Objective C) it is allowed to declare local variables in the inner scope that would hide variables of the outer scope. You can get rid of if
and write this:
int i = 0;
{
// Here, the outer i becomes inaccessible
float i = 1.1;
{
int i = 2;
printf("%d", i); // 2 is printed
}
}
C# standard decided against that, probably because it has a high probability of being an error, but C/Objective C does not have a problem with it.
Upvotes: 4
Reputation: 59287
You're partially correct, yes, it gives i
a new meaning, but it's not redeclaring the variable. It's another variable. But since the identifier is the same, the current scope will "hide" the previous, so any use of i
inside that block refers to the float.
Upvotes: 1