user393267
user393267

Reputation:

(objective-C) Can i use the same variable name in 2 different functions, but in the same file?

Maybe this is implicit, but I am having doubts about it.

I have a .m file that has 2 different functions (or methods, as they are also called); but both functions uses a variable that I declare locally inside each function.

For sake of clarity, I like to use the same name; and from what I understand; there should be no problem in having both functions having the same variable name, since they will point to 2 different pointer locations in memory, so it should not matter.

Am I missing something or it is safe to do what I am doing? Should I use a different name? Should I use a global and change it accordingly, locally?

-(int) doThis
{

    int pressure = 1;

    ...do the calculations and return the results...

}

-(int) doThat
{

    int pressure = 5;
    ...do the calculations and return the results....

}

Upvotes: 3

Views: 2673

Answers (1)

Hermann Klecker
Hermann Klecker

Reputation: 14068

Yes, certainly.

You could even use the same variable name within different scopes in the same method.

Sample:

-(int) doThat
{

    int pressure = 5;

    for (int i = 0, i < pressure, i++) {
        int pressure = 10; // This is another variable!!! 
        pressure = 15;
        //Whatever
    }

    return pressure; //This would return 5!
}

I did that some times unintentionally. The errors that may result of that can be a pain in the a.. because they can be hard to see.

Just to add some more confustion: All within the same class, you could have an instance variable pressure which would hide a global variable pressure, if any. A method named pressure may have a parameter pressure which hides the instance variable. Then you may declare several variables pressure within different scopes within that method. All of them would hide their individually named counterparts in of the enclosing scope. And if you really want it confusing, then add a property named pressure to it. And that all may even work fine until you start loosing control or re-visit the same code a couple of weeks later.

Edit: the method pressure would clearly conflict with the getter of the property pressure. Meaning, it would work but the compiler would take the method as the getter given that it returns an object of the appropritate type. Or so.

Upvotes: 8

Related Questions