C++ - 变量

一.什么是变量?

存在内存中可以修改的量叫做变量,变量有许多类型,整型,浮点型,布尔型等等。变量也可以分为全局变量和局部变量,前者可以在全文使用,后者只能在特定的区域使用。

二.变量的定义

int x{10};

注意:在C++中,定义一个变量一定要赋给它具体的值,否则编译器直接报错。

三.变量的强制转换

(想要转换成的类型)变量名。

代码演示:

复制代码
#include <iostream>
using namespace std;
int main()
{
	//定义一个int类型的变量x
	//如果不给他初始化值那这个值不确定,新版本编译器打印时直接报错。
	int y;
	int x{ 100 };
	cout << "变量x的值为" << 100 << endl;
	//通过变量前加&符号获取变量的内存地址
	//简单的强制转换
	cout << "变量x的内存地址" << (long long)&x << endl;
	int z{ 200 };
	cout << " 变量z的内存地址" << &z << endl;
	cout << "int x的内存大小" << sizeof(x) << endl;
	long long bight{ 0 };
	cout << "long long bight 内存大小" << sizeof(bight) << endl;
  return 0;
}

四.变量的算数运算

变量的算数运算支持变量和字面量,也支持自增和自减运算。

代码演示:

复制代码
#include <iostream>
using namespace std;
//全局变量
//作用域,在不做声明的情况下在本文都可以访问。
//生命周期:main函数执行结束后释放空间。
int gx{ 0 };
int main()
{
	cout << "gx = " << gx << endl;
	//局部变量
	//作用域在定义变量所属的{}内部
	//从变量定义开始到}结束
	int py{ 50 };
	cout << "py = " << py << endl;

	//运行时常量
	const int cx{ 100 };
	cout << "cx = " << cx << endl;
	//cx = 200;//修改编译报错
	constexpr int cex{ 300 };
	cout << "cex = " << cex << endl;
	int t1 = 10;
	const int cx2{ t1 + 10 };//执行时常量可以用变量初始化
	cout << "cx2 = " << cx2 << endl;
	//constexpr int cex2{t1 * 10};//无法用变量初始化编译时常量,必须在编译时就知道值

	//一般情况下用编译时常量,涉及参数传递时用执行时常量。
	return 0;
}

四.常量

分类:

1.const int{x} - 运行时常量 - 可以用变量初始化

2.constexpr int{x} - 编译时常量 - 不能用变量初始化

代码:

复制代码
#include <iostream>
using namespace std;
//全局变量
//作用域,在不做声明的情况下在本文都可以访问。
//生命周期:main函数执行结束后释放空间。
int gx{ 0 };
int main()
{
	cout << "gx = " << gx << endl;
	//局部变量
	//作用域在定义变量所属的{}内部
	//从变量定义开始到}结束
	int py{ 50 };
	cout << "py = " << py << endl;

	//运行时常量
	const int cx{ 100 };
	cout << "cx = " << cx << endl;
	//cx = 200;//修改编译报错
	constexpr int cex{ 300 };
	cout << "cex = " << cex << endl;
	int t1 = 10;
	const int cx2{ t1 + 10 };//执行时常量可以用变量初始化
	cout << "cx2 = " << cx2 << endl;
	//constexpr int cex2{t1 * 10};//无法用变量初始化编译时常量,必须在编译时就知道值

	//一般情况下用编译时常量,涉及参数传递时用执行时常量。
	return 0;
}

五.auto

1.什么是auto?

auto是C++11的新特性,是一个类型推导的关键字,编译器根据初始化表达式自动推断变量的类型。

2.代码演示:

复制代码
#include <iostream>
using namespace std;
int main()
{
	auto a1 = 10;
	auto d1 = 9.;
	auto f1 = 8.f;
	const int cex{ 10 };
	auto acex = cex;//auto推导常量会变成普通变量。
	//constexpr auto c1 = cex; - 编译常量不能用普通常量赋值。
	const auto c2 = a1;
	auto a3{ 11.3 };
	auto a4 = 14LL;
	auto a5 = (int)d1;//auto也支持强制转换

	return 0;
}
相关推荐
傻啦嘿哟1 小时前
天气数据爬虫:基于Scrapy爬取全国天气,做可视化大屏
c++·爬虫·scrapy
撸串-研究生1 小时前
面向景区的综合服务管理平台设计——以稻城亚丁景区为例【附源码】
java·开发语言·vue.js·前后端分离·稻城亚丁景区
wuyk5551 小时前
样章-第03讲-FreeRTOS在16KB-RAM上的裁剪与陷阱
c语言·开发语言·stm32·单片机·嵌入式硬件·物联网·系统架构
kiros_wang1 小时前
网络状态监听&WiFi信息获取:弱网提示、断网兜底方案
开发语言·网络·php
geovindu1 小时前
rust: pool Pattern (续)
开发语言·后端·设计模式·rust·对象池简写模式
夏虫不可与之言冰1 小时前
使用Flash Download Tool给ESP32烧录固件
c语言·c++·windows·单片机·物联网·iot
一条泥憨鱼1 小时前
拦截器与过滤器:一次请求穿过 Spring 时,会先经过谁呢
java·开发语言·后端·spring
晴天的雨.9921 小时前
【C++】 priority_queue知识点总结
开发语言·数据结构·c++
小七在进步1 小时前
C++内存管理:new/delete vs malloc/free深度解析
android·java·c++