C语言入门篇--四大常量(字面,const修饰,宏,枚举)及标识符

Faith ·
更新时间:2024-09-20
· 1642 次阅读

目录

1.字面常量

2.const修饰的常变量

3.#define定义的标识符常量

3.1标识符

3.2宏常量

4.枚举常量

1.字面常量

(1)字面意思是啥就是啥,看其表示就可以知道其值和类型。

(2)有值无名,一用来初始化变量,与一种字符相关联。

#include <stdio.h> int main() { 10;//int型数字10 'c';//char型字符c "Hello world!";//字符串常量(!C语言无字符串类型) int sum=10+20;//10,20为字面常量可直接用 int a=10;//与一种字符相关联 return 0; } 2.const修饰的常变量

(1)常变量:C语言中,把用const修饰的变量称为常变量。

(2)常变量具有常量属性,不可被直接修改(可间接修改,后续博客说明)。

(3)const---->C语言关键字之一。

#include <stdio.h> int main() { const int x = 100;//也可写成:int const x = 100; x = 200;//error! return 0; }

3.#define定义的标识符常量 3.1标识符

(1)标识符即对变量、函数、文件等的命名名称。

(2)C语言中的标识符只能由字母(a-z)(A-Z)、数字和下划线(_)组成,且第一个字符必须是字母或下划线。

(3)标识符中区分大小写(eg:age、Age、aGe不相同)。

(4)标识符不能与C编译系统预定义的标识符或关键字同名。

(5)标识符命名要做到----见名知意。

3.2宏常量

宏常量:即宏定义的标识符常量,相当于对一个字面常量“宏常量”重命名。

eg:#define Age 21(!没有 ; 号 )

以下通过三组例子说明其使用方法及注意事项:

(1)宏常量可当作常量进行赋值操作。

#include <stdio.h> #define Age 21 int main() { printf("%d\n", Age); int x=Age;//可当作常量赋值 printf("%d\n", x); return 0; }

(2)宏可在任何位置出现,但只在宏定义及其往后才可用。

#include <stdio.h> int main() { printf("%d\n", Age);//error! #define Age 21 return 0; }

(3)宏 一旦定义好,不可再程序中修改。若要修改只用改#define后面的值,提升了代码的可维护性。

#include <stdio.h> #define Age 21 int main() { Age = 18;//error! return 0; }

4.枚举常量

枚举即一一列举

eg:

#include <stdio.h> enum color//自定义类型---->枚举类型 { Yellow,//枚举常量 Black, Green, Orange }; int main() { enum color a = Yellow;//Yellow在此为常量 return 0; }

编译通过:

以上就是C语言入门篇--四大常量(字面,const修饰,宏,枚举)及标识符的详细内容,更多关于C语言的资料请关注软件开发网其它相关文章!



C语言入门 枚举 常量 C语言 const

需要 登录 后方可回复, 如果你还没有账号请 注册新账号