目录
一.常量
常量有以下四种类型:
1.字面常量
10;//整形常量
3.14;//浮点型常量
'a';//字符型常量
"abcdef";//字符串常量
这些常量常用作赋值给变量
2.const修饰的常变量
const是C语言中的关键字,被const修饰的变量具有了常属性,也就是拥有了常量的部分性质,但被修饰的变量本质上还是属于变量
int num = 10;
printf("%d\n",num);
num = 20;//修改num的值为20
printf("%d\n",num);
变量没被const修饰之前是可以修改的
const int num = 10;
printf("%d\n",num);
num = 20;
printf("%d\n",num);
而变量被const修饰后再修改它的值就会报错,说明被const修饰后的变量变成了值不能被修改的常变量
为什么说它是常变量呢?下面是它和常量的区别:
int arr[10] = { 0 };
以这种方式创建数组是没有问题的
int n = 10;
int arr[n] = { 0 };
以这种方式创建数组就会报错,说明再[ ]中应该放入一个常量
const int n = 10;
int arr[n] = { 0 };
被const修饰后仍然会报错,说明被const修饰的变量本质上还是变量
3.#define定义的标识符常量
define定义的标识符常量就是一个彻彻底底的常量
#define NUM 10
int a = NUM;
int arr[NUM] = { 0 };
printf("%d\n",a);
这次没有报错,代码正常运行