![](/img/trans.png)
[英]Is a local scoped variable initialized to an undetermined value, or un-initialized?
[英]Get the middle scoped value of variable
假設這是一段代碼,以演示如何使用局部和全局變量。 我試圖向一個小伙子解釋這個問題,他問了我這個問題。
在下面的代碼中,您應該怎么做才能從外循環中獲取“ x”的值。 在這種情況下,如何訪問值為2的“ x”。
#include<iostream>
using namespace std;
int x = 1;
void fun() {
int x = 2;
{
int x = 3;
cout << x << endl; // This will give 3
cout << ::x << endl; // This will give 1
// What should I write here to get x = 2.
}
}
int main() {
fun();
}
你不能 第一個x
的名稱已被第二個x
隱藏。 由於第一個x
不屬於名稱空間(包括全局名稱空間),類或枚舉,因此您無法限定其名稱,因此無法訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.