Scope rules in C: Nested blocks

时光毁灭记忆、已成空白 提交于 2019-12-10 15:21:17

问题


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?


回答1:


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)

  • declare a pointer, assign the address of the outer variable to it.
  • declare and define the local variable.
  • use both.

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.



来源:https://stackoverflow.com/questions/30588599/scope-rules-in-c-nested-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!