In general, bit fields are used as a way to store data more tightly.
Program Listing 15.3 FIELDS.C
1#include <stdio.h>2#include <stdbool.h>3 //the style of the line4 #defineSOLID 0//Solid Line5 #defineDotted 1//Point Line6 #defineDashed 2//Dashed Lines7 //Three primary Colors8 #defineBLUE 49 #defineGREEN 2Ten #defineRED 1 One //Mixed Color A #defineBLACK 0 - #defineYELLOW (red| GREEN) - #defineMAGENTA (red| BLUE) the #defineCYAN (green| BLUE) - #defineWhite (red| green| BLUE) - - Const Char* colors[8] = {"Black","Red","Green","Yellow", + "Blue","Magenta","Cyan"," White" }; - + structBox_props { A BOOLOpaque:1;//whether the box is transparent atUnsignedintFill_color:3; -Unsignedint:4;//gaps between each byte are populated with unnamed fields - BOOLShow_border:1;//borders Show or hide -UnsignedintBorder_color:3; -UnsignedintBorder_style:2; -Unsignedint:2; in }; - to voidShow_settings (Const structBox_props *pb) + { -printf"Box is%s.\n", Pb->opaque = =true?"Opaque":"Transparent"); theprintf"The fill color is%s.\n", colors[pb->Fill_color]); *printf"Border%s.\n", Pb->show_border = =true?"shown":"Not shown"); $printf"The border color is%s.\n", colors[pb->Border_color]);Panax Notoginsengprintf"The border style is"); - Switch(pb->border_style) the { + CaseSOLID: APuts"Solid."); the Break; + CaseDotted: -Puts"dotted."); $ Break; $ CaseDashed: -Puts"dashed."); - Break; the default: -Puts"unknown type.");Wuyi } the } - Wu intMainvoid) - { About structBox_props box = {true, YELLOW,true, GREEN, dashed}; $ -Puts"Original box settings:"); -Show_settings (&box); - ABox.opaque =false; +Box.fill_color =White ; theBox.border_color =MAGENTA; -Box.border_style =SOLID; $Puts"\nmodified box settings:"); theShow_settings (&box); the the return 0; the}
"Reading notes" C Primer Plus ch.15 bit Operation Example program 15.3 defining and using fields