[英]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.