English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about enum (enumeration) in C language programming through examples.
In C language programming, the enum type (also known as enum) is a data type composed of integer constants. To define an enum, the enum keyword will be used.
enum flag {const1, const2, ..., constN};
By default const1For 0, const2For1And so on. You can change the default value of enumeration elements during declaration if necessary.
//Change the default value of enumeration constants enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3, };
When defining an enum type, a blueprint of the variable is created. Below, we will introduce how to create a variable of enum type.
enum boolean {false, true}; enum boolean check; // Declare an enumeration variable
Here, an enum boolean variable check will be created.
You can also declare enumeration variables like this.
enum boolean {false, true} check;
Here, the value of false is equal to 0, and the value of true is1.
#include <stdio.h> enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; int main() { //Create a variable today of type enum week enum week today; today = Wednesday; printf("Day %d", today+1); return 0; }
Output result
Day 4
An enumeration variable can only take one value. This is an example instance of
#include <stdio.h> enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3 } card; int main() { card = club; printf("The size of enumeration variable = %d bytes", sizeof(card)); return 0; }
Output result
The size of enumeration variable = 4 bytes
Here, we get4because the size of int is4bytes.
Let's take an example
enum designFlags { ITALICS = 1, BOLD = 2, UNDERLINE = 4 } button;
Suppose you are designing a button for a Windows application. You can set the flags ITALICS, BOLD, and UNDERLINE to handle text.
In the above pseudocode, all integral constants are2The reason for the power is
//in binary ITALICS = 00000001 BOLD = 00000010 UNDERLINE = 00000100
Since the integral constant is2of powers, so you can combine two or more flags at once without usingbitwise OR |The operator for overlap. This allows you to select two or more flags at once. For example,
#include <stdio.h> enum designFlags { BOLD = 1, ITALICS = 2, UNDERLINE = 4 }; int main() { int myDesign = BOLD | UNDERLINE; // 00000001 // | 00000100 // ___________ // 00000101 printf("%d", myDesign); return 0; }
Output result
5
When the output is5You always know when bold and underline are used.
Additionally, you can add flags as needed.
if (myDesign & ITALICS) { //Italic }
Here, we have added italics in the design. Note that only italic code is written inside the if statement.
You do not need to use enums to complete almost all tasks in C language programming. However, they may be very convenient in some cases.