在C/C++中一般全局變量的值可能被程序中局部變量的值覆蓋,這是爲什麼?
原因:因爲全局變量的賦值是發生在編譯時刻,而程序中局部變量的賦值發生在執行時刻,所以後者覆蓋前者。
有時候局部作用域或着是局部變量搞不清楚容易造成錯誤,如下面例子:
#include <iostream> #include <vector> #include <string> using namespace std; int x=3; int main(int argc, const char * argv[]) { if (1) { int x =2; } cout<<"x="<<x<<endl; return 0; }
這裏的結果竟然是x=3;
#include <iostream> #include <vector> #include <string> using namespace std; int x=3; int main(int argc, const char * argv[]) { if (1) { x =2; } cout<<"x="<<x<<endl; return 0; }
這個結果是x=2;
第一個例子明顯是定義了一個局部變量,然而if語句算是一個作用域,局部變量只作用在自己的作用域內,出了作用域,顯然是全局變量在起作用;第二個一直是全局變量在起作用。