fields.cpp

#include <stdio.h>
#include <stdbool.h>

/* 线的样式 */ 
#define SOLID 0
#define DOTTED 1
#define    DASHED 3

/* 三原色 */
#define BLUE 4                                // 100
#define GREEN 2                                // 010
#define RED 1                                 // 001

/* 混合色 */
#define BLACK 0
#define YELLOW (RED | GREEN)
#define MAGENTA (RED | BLUE)
#define CYAN (GREEN | BLUE)
#define WHITE (BLUE | GREEN | RED)

const char * color[8] = {"black", "red", "green", "yellow",
"blue", "magenta", "cyan", "white"}; 

struct box_props {
    bool opaque                    : 1;
    unsigned int fill_color      : 3;
    unsigned int                 : 4;        //未命名字段进行填充 
    bool show_border            : 1;
    unsigned int border_color     : 3;
    unsigned int border_style    : 2;
    unsigned int                 : 2;
};

void show_settings(const struct box_props *pb);

int main()
{
    /* 创建并且初始化 box_props 结构 */ 
    struct box_props box = {
        true,
        YELLOW,
        true,
        GREEN,
        DASHED 
    };
    
    printf("Original box seetings: \n");
    show_settings(&box); 
    
    box.opaque = false;
    box.fill_color = WHITE;
    box.border_color = MAGENTA;
    box.border_style = SOLID;

    printf("\nModified box settings: \n");
    show_settings(&box);
    
    return 0;
}

void show_settings(const struct box_props *pb)
{
    printf("Box is %s.\n", pb->opaque == true ? "opaque" : "transparent");
    printf("The fill color is %s.\n", color[pb->fill_color]);
    printf("Border is %s.\n", pb->show_border == true ? "shown" : "not shown");
    printf("Border color is %s.\n", color[pb->border_color]);
    printf("Border style is ");
    switch(pb->border_style)
    {
        case SOLID:
            printf("solid.\n");
            break;
        case DOTTED:
            printf("dotted.\n");
            break;
        case DASHED:
            printf("dashed.\n");
            break;
        default:
            printf("unknown type.\n");    
    }
}

标签: C

添加新评论