常量
- 在程序运行过程中,其值不能被改变的量
- 常量一般出现在表达式或赋值语句中
- 不过,只读变量实际上也有自己的内存空间,而且我们也是有办法强行修改它的值的
| 整型常量 | 100,200,-100,0 |
|---|---|
| 实型常量 | 3.14 , 0.125,-3.123 |
| 字符型常量 | ‘a’,‘b’,‘1’,‘\n’ |
| 字符串常量 | “a”,“ab”,“12356” |
define、const(不推荐)
#include <stdio.h>#define PI 3.1415// const float PI = 3.1415; //不推荐int main(void){const int r = 3; // 定义一个只读变量//圆的面积 = PI x 半径的平方float s = PI * r * r;//圆的周长 = 2 x PI x 半径float l = 2 * PI * r;printf("圆的周长为:%f\n", l); // 默认显示 6 位小数。printf("圆的面积为:%f\n", s);printf("圆的周长还可以写成:%.2f\n", PI * r * r);printf("圆的面积还可以写成:%.2f\n", 2 * PI * r); // 指定保留小数点后保留2位,对第3位k进行4舍五入return 0;}
#include <stdio.h>int main() {const int kRed = 0xFF0000;int* p = &kRed;*p = 0;printf("value of kRed is: %d\n", kRed);return 0;}
#include <stdio.h>#define COLOR_RED 0xFF0000#define COLOR_GREEN 0x00FF00#define COLOR_BLUE 0x0000FFint main() {// const <type> readonly variableconst int kRed = 0xFF0000;const int kGreen = 0x00FF00;const int kBlue = 0x0000FF;printf("kRed: %d\n", kRed);int *p_k_red = &kRed;*p_k_red = 0;printf("kRed: %d\n", kRed);// macroprintf("COLOR_RED: %d\n", COLOR_RED);#undef COLOR_RED// 字面量 literal3;3u;3l;3.f;3.9;'c';"cs";L'中';L"中国";// 硬编码 hard codeint background_color = COLOR_GREEN;return 0;}
