广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++变量存储的生命周期与作用域实例代码精讲
  • 728
分享到

C++变量存储的生命周期与作用域实例代码精讲

C++变量存储生命周期C++变量存储作用域 2022-11-13 18:11:02 728人浏览 薄情痞子
摘要

auto类型:非静态的局部变量存储类型都是auto,这些数据存储在栈区,不初始化变量的值时随机的。c++中的auto还可以自动推导类型。生命周期:块内 作用域:块内 程序: #inc

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++变量存储的生命周期与作用域实例代码精讲的文章就介绍到这了,更多相关C++生命周期与作用域内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C++变量存储的生命周期与作用域实例代码精讲

本文链接: https://www.lsjlt.com/news/170201.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作