【初识C语言】常量(字面常量、const修饰的常变量、宏定义的标识符常量(宏常量)、枚举常量)、标识符

常量(4种)

常量,即不可被直接修改的量(const修饰的常变量可间接修改,后续博客说明)。

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;
	
}

编译通过:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46630468/article/details/113132790
今日推荐