栋察宇宙(五十二):C语言常量
发布时间:2026-02-26 22:20 浏览量:1
分享兴趣,传播快乐,增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来
“C语言常量”。
欢迎您的访问!
Share interest, spread happiness, increase knowledge, and leave beautiful.
Dear, this is the LearingYard New Academy!
Today, the editor brings the "Constants in C Language".
Welcome to visit!
思维导图
Mind mapping
常量是C语言中值在程序运行过程中不可修改的固定数据。它与变量相对应,占据固定的内存空间,是程序中不变值的核心表达形式。合理使用常量可提升代码可读性,避免魔法数字(无意义字面量)导致的维护难题。
A constant is fixed data whose value cannot be modified during program operation in the C language. Corresponding to variables, it occupies fixed memory space and is the core expression form of invariant values in programs. Reasonable use of constants can improve code readability and avoid maintenance problems caused by magic numbers (meaningless literals).
常量的分类
Classification of Constants
1. 字面常量:直接书写在代码中的固定值,无需提前定义即可使用。根据数据类型可分为:整型常量(如100、0x1A)、浮点型常量(如3.14、1.23e5)、字符常量(如'a'、'\n')、字符串常量(如"hello"、"")。
1. Literal Constants: Fixed values directly written in the code, which can be used without prior definition. According to data types, they can be divided into: integer constants (e.g., 100, 0x1A), floating-point constants (e.g., 3.14, 1.23e5), character constants (e.g., 'a', '\n'), string constants (e.g., "hello", "").
2. 符号常量:用标识符替代字面常量,通过预处理指令#define定义(又称宏常量),语法格式为#define 常量名 常量值(末尾无分号),例如#define PI 3.14159。预处理阶段会将代码中所有常量名替换为对应值,无类型检查。
2. Symbolic Constants: Literal constants are replaced by identifiers, defined through the preprocessing directive #define (also known as macro constants). The syntax format is #define CONSTANT_NAME CONSTANT_VALUE (no semicolon at the end), e.g., #define PI 3.14159. All constant names in the code will be replaced with corresponding values during the preprocessing stage, with no type checking.
3. 常变量:用const关键字修饰的变量,值不可修改且具有类型属性,语法格式为const 数据类型 变量名 = 初始值(必须初始化),例如const int limit = 50。与符号常量相比,常变量受类型检查,作用域可通过代码块限制。
3. Constant Variables: Variables modified with the const keyword, whose values cannot be modified and have type attributes. The syntax format is const data_type variable_name = initial_value (must be initialized), e.g., const int limit = 50. Compared with symbolic constants, constant variables are subject to type checking, and their scope can be limited by code blocks.
4. 枚举常量:通过enum关键字定义的一组命名整数常量,适用于有限取值场景,语法格式为enum 枚举名 {常量1, 常量2, ...}(默认从0开始递增),例如enum Week {Mon, Tue, Wed}。也可自定义初始值,如enum Color {Red=1, Green, Blue}。
4. Enumeration Constants: A set of named integer constants defined by the enum keyword, suitable for scenarios with limited value ranges. The syntax format is enum Enum_Name {CONST1, CONST2, ...} (defaults to incrementing from 0), e.g., enum Week {Mon, Tue, Wed}. Custom initial values are also allowed, such as enum Color {Red=1, Green, Blue}.
常量的核心特性
Core Characteristics of Constants
1. 不可修改性:所有常量的值在程序运行期间均无法被赋值语句修改,尝试修改会触发编译器错误,例如const int a=10; a=20;会直接报错。
1. Immutability: The values of all constants cannot be modified by assignment statements during program operation, and attempting to modify them will trigger a compiler error, e.g., const int a=10; a=20; will directly report an error.
2. 内存占用:字面常量和符号常量无独立内存(仅为预处理阶段的文本替换),而常变量和枚举常量会占用固定的内存空间;符号常量编译后无“常量名”相关信息。
2. Memory Occupancy: Literal constants and symbolic constants have no independent memory (only text replacement during the preprocessing stage), while constant variables and enumeration constants occupy fixed memory space; there is no information related to "constant names" for symbolic constants after compilation.
3. 类型属性:常变量和枚举常量有明确的数据类型,编译器会进行类型检查;而符号常量无类型属性,仅做文本替换,例如#define NUM 5.8; int a=NUM;不会触发类型错误,而const double num=5.8; int a=num;会提示类型转换警告。
3. Type Attribute: Constant variables and enumeration constants have clear data types, and the compiler will perform type checking; symbolic constants have no type attributes and only perform text replacement. For example, #define NUM 5.8; int a=NUM; will not trigger a type error, while const double num=5.8; int a=num; will prompt a type conversion warning.
常量使用的核心注意事项
Key Notes for Constant Usage
1. 避免魔法数字:所有固定值优先定义为符号常量或常变量,例如将if (score > 90)优化为#define PASS_SCORE 90; if (score > PASS_SCORE),提升代码可读性和可维护性。
1. Avoid Magic Numbers: All fixed values are preferably defined as symbolic constants or constant variables. For example, optimize if (score > 90) to #define PASS_SCORE 90; if (score > PASS_SCORE) to improve code readability and maintainability.
2. 常量类型选择:简单固定值优先使用#define,需要类型检查或局部作用域限制时使用const,枚举常量适用于状态、选项类场景(如星期、颜色、错误码)。
2. Selection of Constant Types: Use #define for simple fixed values, const when type checking or local scope restrictions are needed, and enumeration constants for state and option scenarios (such as weeks, colors, error codes).
3. 常变量必须初始化:const修饰的变量定义时必须赋值,否则编译器报错,错误示例为const int num;,正确示例为const int num=100;。
3. Constant Variables Must Be Initialized: Variables modified with const must be assigned values at definition, otherwise the compiler reports an error. An error example is const int num;, and a correct example is const int num=100;.
4. 字符串常量不可修改:字符串常量存储在只读内存区,尝试修改会导致程序崩溃(如char *str="test"; str[0]='T';);如需修改字符串,需定义字符数组(如char str="test"; str[0]='T';)。
4. String Constants Cannot Be Modified: String constants are stored in the read-only memory area, and attempting to modify them will cause program crashes (e.g., char *str="test"; str[0]='T';); to modify a string, define a character array (e.g., char str="test"; str[0]='T';).
总结
Summary
C语言常量分为字面常量、符号常量、常变量、枚举常量四类,核心特性是值不可修改。其中符号常量(#define)无类型检查,常变量(const)有类型属性,枚举常量适用于有限取值场景。合理使用常量可避免魔法数字,提升代码可读性和可维护性,需根据实际场景选择合适的常量类型。
Constants in C language are divided into four categories: literal constants, symbolic constants, constant variables, and enumeration constants, with the core characteristic of unmodifiable values. Among them, symbolic constants (#define) have no type checking, constant variables (const) have type attributes, and enumeration constants are suitable for limited value scenarios. Reasonable use of constants can avoid magic numbers and improve code readability and maintainability, and the appropriate constant type should be selected according to actual scenarios.
今天的分享就到这里了,
如果您对文章有独特的想法,
欢迎给我们留言。
让我们相约明天,
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
翻译:文心一言
参考资料:百度百科
本文由LearningYard新学苑整理并发出,如有侵权请后台留言沟通。
文案&排版|qiu
审核|song