search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C/C++ 變數 生命週期/可視範圍 – jashliao部落格

C/C++ 變數 生命週期/可視範圍


資料來源: https://dywang.csie.cyut.edu.tw/dywang/clanguage/node125.html
線上編譯器: https://www.tutorialspoint.com/compile_c_online.php


變數種類

    區域變數 (local variable):生命週期只限函式執行期間,退出函式後即不再有效。 [可視範圍: 函數本身(宣告之後的程式碼)]

    全域變數 (global variable):宣告在函式外,每個函式都可使用此變數。 [可視範圍: 宣告之後的程式碼]
    靜態變數 (static variable):類似區域變數,但靜態變數在編譯時配置固定的記憶體空間,所以即使退出函式,變數的值還是可以保留下來。 [可視範圍: 函數本身(宣告之後的程式碼)]


Code:

#include 

int x, y;//全域變數

void swap(void) {
	int temp;
	temp = x;
	x = y;
	y = temp;
	return;
}

main() {
	printf("Enter TWO integers: \n");
	x=12;y=56;

	printf("Before swap, x = %d, y = %d\n", x, y);
	swap();
	printf("After swap, x = %d, y = %d\n", x, y);
}
/*
Enter TWO integers: 12 56
Before swap, x = 12, y = 56
After swap, x = 56, y = 12
*/


#include 

int increament(void) {
	static int i=0;//靜態變數

	return i++;
}
 
main() {
	printf("i = %d\n", increament());
	printf("i = %d\n", increament());
	printf("i = %d\n", increament());
	printf("i = %d\n", increament());
}
/*
i = 0
i = 1
i = 2
i = 3
*/




熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦