crizzwald
crizzwald

Reputation: 1037

Objective-C Variable Declaration Confusion

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

Answers (4)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

Turn on "Hidden local variables" in your build settings to get a warning.

Upvotes: 3

Kitsune
Kitsune

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

Sergey Kalinichenko
Sergey Kalinichenko

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
    }
}

demo

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

sidyll
sidyll

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

Related Questions