C++ 常量

1.4 常量

作用:用于记录程序中不可更改的数据

C++定义常量的两种方式

  1. #define宏常量:#define 常量名 常量值
    • 通常在文件上方定义,表示一个常量
  2. const修饰的变量const 数据类型 常量名 = 常量值
    • 通常在变量定义前加关键字const,修饰该变量为常量,不可修改

示例

#include <iostream>
using namespace std;

// 常量的定义方式
// 1、#define 宏常量
// 2、const修饰的变量


// 1、#define 宏常量
#define Day 7

int main()
{
	// Day = 14; // 错误,Day是常量,一旦修改就会报错
	cout << "一周总共有:" << Day <<  "天" << endl;

	// 2、const修饰的变量
	const int month = 12;
	// month = 24; // 错误,const修饰的变量也称为常量

	cout << "一年总共有:" << month << "个月份" << endl;
	system("pause");

	return 0;
}
posted @ 2021-12-26 13:57  萨塔妮娅  阅读(76)  评论(0编辑  收藏  举报