奇書共賞第十天,可惜螞蟻書已經不再更新不然許多地方講得很不錯,但現在已經不是1980年而是2020年CS101老早就把課程語言換成Python,今天來看看範例6.12
範例第一段意思大概是這樣,當全域或Main函數與Main函數裡的New Scop都宣告一個變數x時,並不會產生錯誤它們雖然同名但卻是不同變數有各自的記憶體位置,在當程式運行到New Scop時會顯示New Scop裡的x=7, 回到Main函式則會顯示x=5
#include <iostream>
using std::cout;
using std::endl;
int x = 1; // global variable
int main()
{
int x = 5; // local variable to main
cout << "local x in main's outer scope is " << x << endl;
cout << &x << endl;
{ // start new scope
int x = 7; // hides x in outer scope
cout << "local x in main's inner scope is " << x << endl;
cout << &x << endl;
} // end new scope
cout << "local x in main's outer scope is " << x << endl;
} // end main