在C语言中,常量是指在程序运行时其值无法被修改的量。C语言中的常量可以分为以下几种类型:
1. 字面常量
字面常量包括整型常量、实型常量和字符型常量。在代码中直接写明的数值或字符即为字面常量。
#include <stdio.h>
int main(){
	// 字面常量
	3.14; // 实型常量
	1000; // 整型常量
	'a'; // 字符型常量
}
 
2. 多种方式定义常量
2.1 使用#define
使用#define来定义常量,也称为宏定义,将一个标识符表示为一个常量值,在代码中使用时将其替换为常量值。
#include <stdio.h>
#define ZERO 0   // #define的标识符常量
int main() {
	printf("zero = %d\n", ZERO);
    return 0;
}
 
2.2 使用const限定符
const关键字在C99中引入,可以定义常量,对应的是一种更安全、更可控的定义方式。
#include <stdio.h>
int main(){
	// const 修饰的常变量
	const float PI = 3.14f;
	// PI = 5.14; // 不能直接修改!
	return 0;
}
 
2.3 定义枚举常量
使用enum定义枚举类,其中括号中的内容是枚举常量。
#include <stdio.h>
enum Sex{
    // MALE, FEMALE, SECRET 是枚举常量
	MALE,
	FEMALE,
	SECRET
};
int main(){
	// 枚举常量
	printf("%d\n", MALE);
	printf("%d\n", FEMALE);
	printf("%d\n", SECRET);
	// 注:枚举常量默认从0开始递增
	return 0;
}










