您好,我想知道如何在 block 内引用变量“x”(主函数的):
#include <stdio.h>
int x=10; // Global variable x ---> let it be named x1.
int main()
{
int x=5; // main variable x with function scope ---> let it be named x2.
for(x=0;x<5;x++)
{
int x=2; // variable x with block scope ---> let it be named x3.
printf("%d\n",x); // refers to x3
printf("%d\n",::x); // refers to x1
// What is the syntax to refer to x2??? how should I try to access x2?
}
}
最佳答案
对于C
您不能在 main 中访问 x1。局部变量比全局变量具有更高的优先级。 主函数的 x,即 x2 可以在 for block 之外或之前访问。
对于 C++
C++ 具有命名空间的特性,您可以通过命名空间将特定的类/变量等分组到一个范围内。
因此,在嵌套命名空间中包含第一个 x1 和 x2(您甚至可以没有它)。
e.g. namespace a { public : int x; namespace b { public : int x; } }
Then to use x1, a::x and to use x2 write a::b:: x;
关于c - 引用 block 作用域外但函数作用域内的变量 (C/C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20165680/