Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how refer to a local variable share same name of a global variable in C? [duplicate]

for example

#include<stdio.h>

int foo = 100;

int bar()
{
    int foo;
    /* local foo = global foo, how to implemented? */
    return 0;
}

int main()
{
    int result = bar();
    return 0;
}

I think in the function bar, calling foo directly will just get the global foo. How can I refer the local foo? I know in C++, there is this pointer. However, does C has something similar?

Thanks a lot!

like image 879
Alfred Zhong Avatar asked Apr 29 '11 03:04

Alfred Zhong


People also ask

Can local and global variables have the same name in C?

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.

Can we access global variable if there is a local variable with same name?

Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.

What happens if a local variable exists with the same name as the global variable you want to access Mcq?

What happens if a local variable exists with the same name as the global variable you want to access? Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable.

How do you access global variable if there is a local variable with same name in Python?

Use built-in function globals() .


1 Answers

No, by declaring foo in bar(), you have taken the global foo out of scope. Inside bar() when you refer to foo you get the local variable.

like image 54
David Heffernan Avatar answered Nov 06 '22 07:11

David Heffernan