初学C语言4
常量
常量分类:1.字面常量 2.const修饰的常变量 3.#define定义的标识符常量 4.枚举常量
①字面常量:
例:3、3.14、100....像这种从字面上理解直接是一个值,为字面常量
②const修饰的常变量
#include<stdio.h> int main() { int num = 4; printf("%d\n",num); num = 8; printf("%d\n",num); return 0; }
若将int num = 4前加上const,即:
#include<stdio.h> int main() { const int num = 4; printf("%d\n",num); num = 8; printf("%d\n",num); return 0; }
运行后程序报错,因为num被const修饰为常变量不可被改变,此时num已经具有了常属性,但num本质上还是变量(const只是让num成为了不能变的量,但依旧为变量,所以叫常变量)
根据常变量举个例子:
#include<stdio.h> int main() { int arr[10] = {0}; return 0; }
#include<stdio.h> int main() { int n = 10; int arr[n] = {0}; return 0; }
运行后报错,因为定义数组时[ ]内应放入常量,n为变量所以代码错误
#include<stdio.h> int main() { const int n = 10; int arr[n] = {0}; return 0; }
用const修饰后,依然报错,因此n虽被修饰,但依旧为变量,不能放在[ ]中
③#define定义的标识符常量
#include<stdio.h> #define MAX 10 int main() { int arr[MAX] = {0}; printf("%d\n",MAX); return 0; }
当用#define定义一个符号后,将其赋值,那么这个符号即为由#define定义的标识符常量
在定义数组时,[ ]中要放置常量,把MAX用#define定义为一个值为10的常量,因此将MAX放入[ ]中后代码正常运行
④枚举常量(枚举——一 一列举)
枚举关键字——enum
enum Color { RED, YELLOW, BLUE }; int main() { enum Color color = BLUE; return 0; }
这个代码的意思为枚举出颜色RED,YELLOW,BLUE,将BLUE赋予给变量color
#include<stdio.h> enum Color { RED, YELLOW, BLUE }; int main() { printf("%d\n",RED); printf("%d\n",YELLOW); printf("%d\n",BLUE); return 0; }
由此可见,枚举出的RED,YELLOW,BLUE都有一个固定的值,因此赋予color的其实是一个数值