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++中如果一定要去访问寄存器变量那么寄存器变量会被降级成普通变量。寄存器变量不能作为全局变量

程序:

#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);  局部变量访问不了
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

划水猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值