飞书文档https://x509p6c8to.feishu.cn/wiki/MnkLwEozRidtw6kyeW9cwClbnAg
C 常量
常量是固定值,在程序执行期间不会改变,可以让我们编程更加规范。
常量可以是任何的基本数据类型,比如整数常量、浮点常量、字符常量,或字符串字面值,也有枚举常量。
常量就像是常规的变量,只不过常量的值在定义后不能进行修改。
定义常量
在 C 中,有两种简单的定义常量的方式:
- 使用 const 关键字。
- 使用 #define 预处理器。
const 关键字
您可以使用 const 前缀声明指定类型的常量,如下所示:
const type variable = value; |
具体请看下面的实例:
#include <stdio.h>int main()
{const int LENGTH = 10;const int WIDTH = 5;const char NEWLINE = '\n';int area; area = LENGTH * WIDTH;printf("value of area : %d", area);printf("%c", NEWLINE);return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
value of area : 50
请注意,把常量定义为大写字母形式,是一个很好的编程习惯。
#define 预处理器
下面是使用 #define 预处理器定义常量的形式:
关键词 常量名 常量值 |
具体请看下面的实例:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'int main()
{int area; area = LENGTH * WIDTH;printf("value of area : %d", area);printf("%c", NEWLINE);return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
value of area : 50