static 關鍵字.
1、static修飾區域變數;
① 整個生命周期延長,
② 靜態區域變數只會被初始化一次,以后每一次呼叫靜態區域變數,就會使用上一次呼叫完保存的值,
③ 只能被作用域的變數和函式訪問,雖然存在于程式的整個生命周期,但不能被其他函式、檔案訪問,
//沒有static修飾變數
#include<stdio.h>
#include<windows.h>
int func(int c){
int a = 0;
int b = 3;//修飾
int sum;
a++;
b++;
sum =a + b + c;
return sum;
}
int main()
{
int c = 1;
for (int i = 1; i <= 4;i++){
printf("%d\n",func(c));
}
system("pause");
return 0;
}
//輸出結果為6
6
6
6
請按任意鍵繼續. . .
static修飾變數;
#include<stdio.h>
#include<windows.h>
int func(int c){
int a = 0;
static int b = 3;
int sum;
a++;
b++;
sum =a + b + c;
return sum;
}
int main()
{
int c = 1;
for (int i = 1; i <= 4;i++){
printf("%d\n",func(c));
}
system("pause");
return 0;
}
//輸出結果為:
6
7
8
9
請按任意鍵繼續. . .·
2、static修飾全域變數
全域變數被static修飾,靜態全域變數只能在其定義的源檔案使用,在同專案的源檔案內不可見,
//test1.c源檔案
#include<stdio.h>
#include<windows.h>
int a = 1;
//我們在test1.c檔案檔案中定義一個整型變數,在test2c中使用
//test2源檔案
#include<stdio.h>
#include<windows.h>
int main(){
extern int a;
printf("%d\n",a);
system("pause");
return 0;
}
//運行結果為
1
請按任意鍵繼續. . .
//運行就會報搓
普通的全域變數對整個工程可見,其他檔案可以使用extern外部宣告后直接使用
下面對上述例子中的變數使用static修飾
//test1.c檔案
#include<stdio.h>
#include<windows.h>
static int a = 1;
//test2.c檔案
#include<stdio.h>
#include<windows.h>
int main(){
extern int a;
printf("%d\n",a);
system("pause");
return 0;
//運行結果會報錯
//1>LINK : fatal error LNK1168: 無法打開 D:\c 語言\VS //code\static\Debug\static.exe 進行寫入========== 生成: 成功 0 個,失敗 1 個,最新 0 個,跳過 0 個 ==========
3、static 修飾函式
static修飾函式,該函式對本源檔案之外的其他源檔案是不可見,當函式不希望被外界所看見就用static修飾這個函式,
//test1.c檔案
#include <stdio.h>
#include<windows.h>
void fun(void)
{
printf("hello\n");
system("pause");
}
//test2.c檔案
#include <stdio.h>
#include<windows.h>
int main(void)
{
fun();
system("pause");
return 0;
}
//運行結果為:
hello
請按任意鍵繼續. . .
沒用static修飾函式,函式是可以被其他檔案呼叫的
下面我們用static對上面的例子中的函式進行修飾
//test1.c檔案
#include <stdio.h>
#include<windows.h>
static void fun(void)
{
printf("hello\n");
system("pause");
}
//test2.c檔案
#include <stdio.h>
#include<windows.h>
int main(void)
{
fun();
system("pause");
return 0;
}
//運行就會報錯
//1>D:\c 語言\VS code\static\Debug\static.exe : fatal error LNK1120: 1 個無法決議的外部命令
//此時的fun()函式只能在test1.c檔案內使用,test2.c是看不見test1.c檔案內的fun()函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/184855.html
標籤:其他
上一篇:JDK動態代理-使用及原理
