###### tags: `sprout` # scope slide: https://hackmd.io/@i2y3z9dITSa_Q_7V7h-AoA/r1yxk-IO8 --廖凰汝-- --- ### 變數的生命週期 變數**活著**的時候我們可以使用 **死後**無人知曉無影無蹤 --- ## Local Variables 活在<font color="#f39">block</font>裡的變數 在block裡宣告 (出生) 出block就死亡 ---- block: 被大括號包起來的區域 <font color="#f39"></font> ```cpp { // This is a block } ``` ```cpp int foo(int n) { // 連同函式主體一起組成的block } ``` ```cpp for (int i=0; i<5; i++) { // 連同for一起組成的block } ``` ---- ```cpp { { int a = 10; // a 出生 std::cout<<a; // print a } std::cout<<a; // 編譯失敗 a 已經死掉 } ``` ---- ```cpp int main() { for (int i=0; i<5; i++) { // 可以使用i } std::cout<<i; // 編譯失敗 i 已經死掉 } ``` ![](https://i.imgur.com/uTQ5MaP.png) ---- What's Wrong? ```cpp #include <iostream> using namespace std; void func() { int weight = 10; } int main() { func(); cout<<"Weight is "<<weight; } ``` ---- What's wrong ![](https://i.imgur.com/oUYOq3y.png) --- ## Global Variables 可以在程式的各個角落使用他 通常宣告在程式的頂部 在block, function 外 ---- ```cpp= #include <iostream> using namespace std; int global = 10; void func1() { global = global + 1; } void func2() { global = global + 2; } void func3() { global = global + 3; } void func4() { global = global + 4; } int main() { func1(); func2(); func3(); func4(); cout<<global; } ``` ---- 全域變數每個地方都可以改 => 出bug機率大 --- 如果local變數的名稱跟global變數相同 1. 編譯會過? 會 2. 那用誰的? 優先使用最後命名的 ```cpp= #include<iostream> using namespace std; int x = 5; // global x int main() { int x = 2; //local x cout << x << endl; // print 2 } ``` --- ## namespace ---- 如果今天你要和一堆人一起寫project 為了避免撞名,該怎麼辦? ```cpp= int chen_max(int x, int y); int lee_max(int x, int y); int wang_max(int x, int y); ``` ---- ```cpp= #include <iostream> namespace chen { int max(int x, int y) { return x>y ? x : y; }; } int main() { // std 也是一個namespace std::cout<<chen::max(3, 5); } ``` ---- ### using namespace [namespace] 所有在[namespace]的名稱都可以使用 ```cpp= #include <iostream> using namespace std; int main() { cout<<"123"; } ``` --- Debug Time 踩地雷 http://codepad.org/fSBwtrnR Make it better: 使用者不能輸入已經顯示的地圖座標。
{"metaMigratedAt":"2023-06-15T06:45:45.784Z","metaMigratedFrom":"Content","title":"scope","breaks":true,"contributors":"[{\"id\":\"8b6cb7cf-d748-4d26-bf43-fed5ee1f80a0\",\"add\":2498,\"del\":282}]"}
    284 views
   owned this note