C言語の静的キーワードパラメータ

静的キーワード。

1.静的はローカル変数を変更します。

①ライフサイクル全体が延長され
ます。②静的ローカル変数は1回だけ初期化され、今後静的ローカル変数が呼び出されるたびに、最後の呼び出し後に保存された値が使用されます。
③スコープ内の変数や関数からのみアクセスでき、プログラムのライフサイクル全体に存在しますが、他の関数やファイルからはアクセスできません。

//没有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.静的はグローバル変数を変更します

グローバル変数は静的によって変更されます。静的グローバル変数は、それらが定義されているソースファイルでのみ使用でき、同じプロジェクトのソースファイルには表示されません。

//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によって外部で宣言された直後に使用できます。

以下は、上記の例の変数に静的変更を使用しています

//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.静的に変更された機能

静的に変更された関数。この関数は、このソースファイル以外の他のソースファイルには表示されません。関数が外部に表示されたくない場合は、静的を使用してこの関数を変更します。

//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
请按任意键继续. . .

関数は静的で装飾されていません。関数は他のファイルから呼び出すことができます。
以下では、静的を使用して上記の例の関数を変更します。

//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()函数

おすすめ

転載: blog.csdn.net/supermanman_/article/details/109139790