C++变量存储的生命周期与作用域怎么应用

这篇文章主要介绍“C++变量存储的生命周期与作用域怎么应用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“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);  局部变量访问不了
}

关于“C++变量存储的生命周期与作用域怎么应用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注蜗牛博客行业资讯频道,小编每天都会为大家更新不同的知识点。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接