Reputation: 1949
I have the following nested function:
int main()
{
int a, b, c;
a = 10;
int foo()
{
int a, b, c;
//some more code here
}
// some more code here
}
Now, I need to assign the variable a
that belongs to foo()
, with the value of the variable a
that belongs to main()
. Basically, something like foo.a = main.a
is what I'm looking for.
Is there any way of doing this kind of assignment? I read through scope rules here and here , but didn't find anything I could use in this situation.
I know that using a nested function is not advisable, but I'm working on preexisting code, and I don't have permission to change the structure of the code.
How do I proceed?
Upvotes: 4
Views: 1635
Reputation: 134336
Keeping apart the nested function part, AFAIK, C
does not provied any direct way to access the shadowed variable.
Primary Advice: Do not use this approach. Always use separate variable names for inner scopes and supply -Wshadow
to gcc
to detect and avoid possible shdowing.
However, just in case, you have to use the same variable names for inner and outer scope and you have to access the outer scope variable from the inner scope, your best bet is to (in this very order, inside the inner block)
Note: As a general word of advice, please try not to write new code (I understand the maintainance part) in this manner. It is both hard to manage and hard to read.
Upvotes: 6