结构类型详解

本文详细介绍了C语言中的枚举、结构和联合。枚举提供了一种定义排比符号量的方式,增强代码可读性;结构允许组合多个数据形成复合类型,便于表达复杂数据;联合与结构类似,但其所有成员共享同一内存空间,常用于查看内存布局或文件操作。
摘要由CSDN通过智能技术生成

文件目录

枚举

程序中出现数字要尽量用符号来表示而非直接把数字出现在程序中(好处:可读性)
这时会使用到int、const等定义变量的关键字
枚举的出现:定义一些排比的符号量 比int、const更加方便

定义格式

enum 枚举名 {元素1,元素2…};

C语言内部enum数据类型一般为int

基本枚举使用

#include <stdio.h>

enum COLOR {
   RED, YELLOW, GREEN};  //声明一种为color的数据类型

int main(int argc, char const *argv[])
{
   
	int color = -1;
	char *colorName = NULL;
	
	printf("输入喜欢颜色代码");
	scanf("%d", &color);
	switch (color) {
   
		case RED: 
			colorName = "red";
			break;
		case YELLOW:
			colorName = "yellow";
			break;
		case GREEN:
			colorName = "green";
			break; 
		default:
			colorName = "unknown";
			break;
	}
	printf("喜欢的颜色:%s", colorName);
	return 0;
}

枚举类型可以作为值

枚举类型可以跟上enum作为类型

#include <stdio.h>

enum color {
    red, yellow, green};

void f(enum color c);

int main(void)
{
   
	enum color t = red;
	
	scanf("%d", &t);
	f(t);
	
	return 0;
}

void f(enum color c)
{
   
	printf("%d\n",c);
}

自动计数的枚举

好处:用枚举类型中最后一个量来定义数组或或实现循环

#include <stdio.h>
enum COLOR {
   RED, YELLOW, GREEN, NumCOLORS};

int main(int argc, char const *argv[])
{
   
	int color = -1;
	char *ColorNames
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值