Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 988
crizzwald Avatar asked Jun 01 '26 06:06

crizzwald


2 Answers

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.

like image 183
Sergey Kalinichenko Avatar answered Jun 03 '26 21:06

Sergey Kalinichenko


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

like image 22
Amin Negm-Awad Avatar answered Jun 03 '26 19:06

Amin Negm-Awad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!