常量的作用:用于记录程序不可更改的数据
C++定义常量的方式:
1、#define宏常量:#define 常量名 常量值
通常在文件上方定义来表示一个常量
2、const修饰的变量:const 数据类型 常量名 = 常量值
通常在变量定义之前加一个const关键字,修该变量为常量,不可修改
#include<iostream> using namespace std; // 常量的定义方式 // 1、#define宏定义 // 2、#const修饰的变量 # define Day 7 // 表示一周共有7天 int main() { // #define宏定义 // Day = 10; // 表达式错误,Day是一个常量,修改就会报错 cout << "一周共有:" << Day << " 天" << endl; // const修饰变量 const int month = 12; // 表示一年共有12个月 // month = 15; // 表达式错误,const修饰的变量为常量 cout << "一年共有:" << month << " 月" << endl; system("pause"); return 0; }
C++ 基础入门篇1.4:使用常量
于 2024-01-01 21:00:42 首次发布
本文介绍了C++中常量的两种定义方式:#define宏定义和const修饰的变量。强调了宏定义常量的全局性和不可修改性,以及const变量的特性及其在程序中的应用。
摘要由CSDN通过智能技术生成