C语言 联合体验证 主机字节序 +枚举

2023-12-13 12:28:42

联合体应用:验证当前主机的大小端(字节序)

在这里插入图片描述

//验证当前主机的大小端
#include <stdio.h>

union MyData
{
    unsigned int data;
    struct
    {
        unsigned char byte0;
        unsigned char byte1;
        unsigned char byte2;
        unsigned char byte3;
    }byte;
};

int main()
{
    union MyData num;
    num.data = 0x12345678;
    if (0x78 == num.byte.byte0)
    {
        printf("小端字节序\n");
    }
    else if (0x78 == num.byte.byte3)
    {
        printf("大端字节序\n");
    }
    return 0;
}

枚举

枚举(Enumeration)是一种在编程语言中表示一组具名常量的数据类型。

//使用枚举包含一周的七个值
#include <stdio.h>

// 定义一个枚举类型
enum Weekday 
{
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
};

int main() 
{
    // 定义枚举变量
    enum Weekday today;
    // 设置枚举变量的值
    today = WEDNESDAY;

    // 使用 switch 语句根据枚举变量的值进行处理
    switch (today) 
    {
    case MONDAY:
        printf("Today is Monday.\n");
        break;
    case TUESDAY:
        printf("Today is Tuesday.\n");
        break;
    case WEDNESDAY:
        printf("Today is Wednesday.\n");
        break;
    case THURSDAY:
        printf("Today is Thursday.\n");
        break;
    case FRIDAY:
        printf("Today is Friday.\n");
        break;
    case SATURDAY:
        printf("Today is Saturday.\n");
        break;
    case SUNDAY:
        printf("Today is Sunday.\n");
        break;
    default:
        printf("Invalid day.\n");
    }

    return 0;
}

枚举常常用于定义一组相关的离散值,比如颜色、星期几、月份等。

详细教程可转

爱编程的大丙

文章来源:https://blog.csdn.net/CYS_2020/article/details/134968210
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。