tigerlion

局部变量

普通的局部变量也叫动态变量,默认有个关键字叫auto,可以省略。有两种形式:
1.函数内的局部变量
2.复合语句内的局部变量:for(int i = 0; i<5; i++){…}


静态局部变量只能在函数内定义,如:static int a;
函数外不能用,但每次调用会保留上一次的值


#include <stdio.h>
void buy() {
	auto int timesAuto = 1;// 普通局部变量(auto可以省略)
	printf("买%d件\n",timesAuto++);

	static int timesStatic = 1;// 静态局部变量
	printf("-----static买%d件\n",timesStatic++);
}

main() {
	int i;
	for(i= 1; i<=5; i++) {
		buy();
	}
}
买1件
-----static买1件
买1件
-----static买2件
买1件
-----static买3件
买1件
-----static买4件
买1件
-----static买5件

全局变量

普通全局变量:函数外定义,各文件都能使用,无需头文件引入,需extern引入
静态全局变量:函数外定义,自己文件内各函数都可使用,其他文件extern也用不了

f2.c

int a = 1;
// 静态全局变量不能在其他文件中使用
static int b = 2;

main.cpp

#include <stdio.h>

int main(int argc, char** argv) {
	extern int a;
	printf("全局变量a = %d\n", a);
//	静态全局变量不能在其他文件中使用
//	extern int b;
//	printf("static全局变量b = %d\n", b);
	return 0;
}

同名变量

局部变量会覆盖同名的全局变量。

#include <stdio.h>
int  n=1;
main() {
	printf("外部变量 n = %d\n",n);
	int  n=2;
	printf("局部变量 n = %d\n", n);
}
外部变量 n = 1
局部变量 n = 2

C语言内存分区

BSS:Block Started by Symbol

分类:

技术点:

相关文章:

  • 2021-07-02
  • 2021-04-12
  • 2021-12-11
  • 2021-12-26
  • 2021-12-26
  • 2021-11-23
  • 2021-07-02
猜你喜欢
  • 2021-11-17
  • 2021-12-07
  • 2022-12-23
  • 2022-01-14
  • 2021-11-26
  • 2022-02-11
  • 2021-12-25
相关资源
相似解决方案