gpt4 book ai didi

c - 如果两者在 C 中具有相同的名称而不使用第三个变量,如何将局部变量复制到全局变量?

转载 作者:太空狗 更新时间:2023-10-29 17:15:35 26 4
gpt4 key购买 nike

我有一个同名的全局变量和一个局部变量。我可以将局部变量复制到全局变量(赋值),而无需先将全局变量的值赋给某个​​临时变量(使用 extern),然后再将临时变量赋给全局变量吗?我需要做这样的事情:

#include<stdio.h>
int myVariable = 50;
void myFunction()
{
int myVariable;
myVariable /*global*/ = myVariable /*local*/;
}

在 C 中有什么方法可以做到这一点(不使用临时变量(或指针,如果是数组))?我发现在 C++、Java 或 C# 中使用 this、super、base 等关键字是可能的,但在 C 中找不到解决方案。

我已经提到了How can I access a shadowed global variable in C?

最佳答案

在 C99 中,无法指定您要使用的变量/常量的具体范围。引用变量/常量时,它会自动引用最内层的作用域。

来自 C99 标准 6.2.1.4:

... If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will be a strict subset of the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope ...

那么我该如何解决这个问题呢?

很简单,更改最内层作用域变量的名称:)

关于c - 如果两者在 C 中具有相同的名称而不使用第三个变量,如何将局部变量复制到全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18239634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com