這篇文章主要介紹“C++變量存儲的生命周期與作用域怎么應用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“C++變量存儲的生命周期與作用域怎么應用”文章能幫助大家解決問題。
auto類型:非靜態的局部變量存儲類型都是auto,這些數據存儲在棧區,不初始化變量的值時隨機的。C++中的auto還可以自動推導類型。生命周期:塊內 作用域:塊內
程序:
#include <stdio.h> void test(void); int main() { // auto存儲類型 auto b = 13; // C++新功能,auto自動推導類型 int a = 12; // auto存儲類型的局部變量,存儲在函數棧幀中 { int c = 11; printf("%d\n",a); printf("%d\n",c); } test(); printf("%d\n",a); return 0; } void test(void) { int d = 13; // auto存儲類型的局部變量,存儲在函數棧幀中 printf("%d\n",d); }
static類型:static靜態存儲類型的變量,可以作為局部變量和全局變量。作為全局變量的時候不能被外部文件所訪問,靜態變量只初始化一次,存儲在靜態區中。也可以用來修飾函數,這樣外部文件無法調用該函數。生命周期:整個程序 作用域:全局靜態文件內、局部塊內
程序:局部靜態變量
#include <stdio.h> #include <windows.h> void test(void); int main() { test(); test(); // printf("%d", a); static作為局部變量,外面是訪問不了的 system("pause"); return 0; } // 局部靜態變量,存儲在靜態區中 void test(void) { static int a = 11; // 只會被初始化一次 a++; printf("%d\n", a); }
程序:全局靜態變量
#include <stdio.h> #include <windows.h> void test(void); static int b = 33; // 全局靜態變量,外部文件無法訪問,存儲在靜態區中 int main() { test(); printf("%d\n", b); system("pause"); return 0; } void test(void) { printf("%d\n", b); }
register類型:寄存器變量,存儲在cpu中不在內存中,所以沒有地址??梢约涌煊嬎銠C訪問。但是在C++中如果一定要去訪問寄存器變量那么寄存器變量會被降級成普通變量。寄存器變量不能作為全局變量
程序:
#include <stdio.h> // register int b = 12; 寄存器變量沒法作為全局變量 int main() { // register變量沒有地址 register int a = 12; printf("%d",a); printf("%p", &a); // 強制訪問register變量,那么這個變量會變為auto類型 for(register int i=0; i<1000; i++){ // 加快運行速度寫法,但是沒必要 } return 0; }
extern類型:可以訪問外部文件中的全局變量,只要在本文件中的變量前加上extern表示他是個外部變量。
程序:
extern.h
#ifndef _EXTER_H_ #define _EXTER_H_ #include <stdio.h> void test1(); #endif
extern_test.cpp
#include "exter.h" int c = 44; int d = 55; // 這里不要寫extern int d;這是錯誤的 ,也不要寫成extern int d=55這個是對的但是不推薦 void test1() { printf("extern_test_c_addr:%p\n", &c); printf("extern_test_d_addr:%p\n", &d); }
man.cpp
#include <stdio.h> #include <windows.h> #include "exter.h" void test(void); extern int d; // extern拿到其他文件變量并作為本文件的全局變量 int main() { // extern拿到其他文件變量并作為本文件的局部變量 extern int c; printf("c=%d\n",c); c = 12; printf("c=%d\n",c); printf("d=%d\n",c); test(); test1(); printf("extern_test_c_addr:%p\n", &c); printf("main_d_addr:%p\n", &d); system("pause"); return 0; } void test(void) { printf("test d=%d\n",d); //printf("c=%d\n", c); 局部變量訪問不了 }
關于“C++變量存儲的生命周期與作用域怎么應用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。