1.4 符号常量
Last updated
Was this helpful?
Last updated
Was this helpful?
It's bad practice to bury "magic numbers" like 300 and 20 in a program; they convey little information to someone who might have to read the program later, and they are hard to change in a systematic way.
Symbolic constant names are convention-ally written in upper case so they can be readily distinguished from lower case variable names. Notice that there is no semicolon at the end of a # d e fi n e line.
符号常量名 通常用大写字母拼写。
这里 magic number 的叫法,后续还会出现。
在这个例子中,我们使用 #define 定义了一个叫做PI的常量,并将其设置为 3.14159。然后在主函数中,我们使用这个常量来计算圆的面积。当编译器遇到PI时,它会自动将其替换为3.14159。
#define 可以用于定义任何类型的常量,无论是整数、浮点数、字符、字符串,甚至是函数宏。它可以在代码中增加可读性,并让你更方便地管理常用的数值或表达式。
请注意,#define 只是进行简单的文本替换,它在编译前处理阶段就会生效,不会进行类型检查。在使用 #define 定义常量时,应该遵循命名规范,以便代码更易读懂。