C:嵌套块中的作用域规则 [英] Scope rules in C: Nested blocks

查看:235
本文介绍了C:嵌套块中的作用域规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的嵌套函数:

  int main()
{
int a, b,c;
a = 10;
int foo()
{
int a,b,c;
//这里有更多的代码
}
//这里有更多的代码
}

现在,我需要分配属于 foo()的变量 a ,变量 a 属于 main()的值。基本上,像 foo.a = main.a 就是我要找的东西。



有没有做这种任务的方式?我阅读了范围规则此处 here ,但在这种情况下没有找到任何可以使用的东西。



我知道使用嵌套函数并不可取,但我正在研究已有的代码,而且我没有权限更改代码的结构。

保留嵌套函数部分,AFAIK, C 不会提供任何访问阴影变量的直接方式。

小学建议:不要使用这种方法。始终为内部作用域使用单独的变量名称并提供 -Wshadow gcc 来检测和避免可能的 shdowing 的。然而,为了以防万一,你必须为内部和外部作用域使用相同的变量名,并且你必须从内部作用域访问外部作用域变量,你的最好的赌注是(在这个顺序中,在内部块内)


  • 声明一个指针,将外部变量的地址赋值给它。

  • 声明并定义局部变量。

  • 同时使用两者。

  • $ b


    注意:作为建议的一般用语,请尽量不写 new 代码(我了解维护部分)以这种方式。这是很难管理和难以阅读。


    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?

    解决方案

    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.

    这篇关于C:嵌套块中的作用域规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆