Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can local variables and functions have the same names in C?

Tags:

c

Suppose I have a single .c file in which I have a local variable a. Can I also have a function in that c file which has the same name a?

EDIT: If not, why?

Conceptually, the local variable is stored on stack and functions are stored in text section of memory. So there shouldn't be a problem right?

When I tried this, compiler gave error. I am wondering if this is compiler specific or it is actually an error.

like image 475
SoulRayder Avatar asked Jan 24 '14 06:01

SoulRayder


People also ask

Can variables and functions have the same name?

Variables and functions have separate name spaces, which means a variable and a function can have the same name, such as value and value(), and Mata will not confuse them.

Can we declare local variables with same name in different functions?

Yes . Local variables overide globals with the same name. Even more, You can have a different variable with the same name inside each scope .

Can functions have the same name in C?

No. In strict C, you cannot do overloading.

Can global and local variables have same name?

It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.


1 Answers

I assume you have something like that:

void a (void)
{
    // whatever
}

int main(void)
{
    int a;
    a++; // no problem, boss
    a(); // <-- compiler tantrum: variable used as a function
    // whatever
}

The error you are getting is due to the fact that you are using a as a function.

Each time you open a curly brace, you define a new local scope, where you are free to redefine symbols that exist in a higher scope.

In that case, the identifier a inside the block is refering to a local variable, so you can't use it as a function.
a at toplevel is a function, but inside the block it is shadowed by the local variable definition with the same name.
It means you cannot call the function a from within that block (and any other embedded sub-blocks, for that matter). (more precisely, you cannot access the function a by its name, but you could still call it by having a pointer to that function accessable from within that scope)

This should be an incentive to define meaningful names for your functions and other global symbols, since they will have to coexist in the toplevel scope and run the risk of being shadowed by any lower scope symbols.

As other answers stated, there are mechanisms in other languages like C++ called "scope resolution modifiers" that allow to explicitely designate the scope of a symbol, but that does not exist in C.

like image 122
kuroi neko Avatar answered Oct 28 '22 12:10

kuroi neko