C++中常量定义
基本知识
- #define宏常量
- const修饰
#define宏常量
语法 | #define 常量名 常量值 |
---|---|
位置 | 文件上方 |
const修饰的变量
语法 | const 数据类型 变量名 = 常量值 |
---|---|
位置 | 文件中 |
测试源代码
/*
时间:2021.02.10
内容:常量定义
*/
/*
常量:
1.#define 宏常量:#define 常量名 常量值
通常在文件上方定义,表示一个常量
2.const修饰的变量:const 数据类型 常量名 = 常量值
通常在变量定义前加关键字const,修饰该变量为常量,不可修改
*/
#include <iostream>
using namespace std;
// #define DAY 7; // error // 去掉分号
#define DAY 7
int main()
{
// DAY = 14; // DAY不能被赋值
cout << "DAY = " << DAY << endl;
const int month = 12;
// month = 1; // month不能被再次赋值
cout << "month = " << month << endl;
system("pause");
return 0;
}
// KEEP CALM AND CARRY ON