[英]Refer to the variable outside block scope but inside function scope ( C/C++)
嗨,我想知道如何在块内引用变量“ x”(main函数的):
#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块之外或之前访问。
对于C ++
C ++具有名称空间的功能,通过该名称空间,您可以将特定的类/变量..etc分组为一个范围。
因此,将第一个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;
在这种情况下,您不能引用x2。 它在局部范围内声明(C除了标签外没有函数范围的概念),并且其声明被内部块中的x3掩盖。 请参阅http://www-01.ibm.com/support/docview.wss?uid=swg27002103&aid=1中第3页的“本地范围”。
x2
和x3
相同。 for
块不是作用域。 当编译器看到以下内容时:
int x = 5;
for(x = 0; x < 5; x++) {
int x = 2;
}
...实际上看到的是:
int x;
x = 5;
for(x = 0; x < 5; x++) {
x = 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.