C Enums

Enum (or enumeration) in C are user-defined data types used to assign names to integral constants. Enums make code easier to understand and maintainable. The keyword "enum" is used to declare an enumeration. By default, the value of the constants starts with 0 and increments by one, however, they can be assigned with a new value.

Syntax


enum enum_name{const1,const2,...};

Example Code

#include<stdio.h>
enum numbers{
	Zero,
	One,
	Two,
	Three,
	};
	
enum custom{
	con1 = 100,  //100
	con2,        //100 + 1
	con3,        //101 + 1
	con4 = 1000, //1000
	con5,        //1000 + 1
	con6         //1001 + 1 
};

int main(void)
{
	enum numbers num;
	num = Three;
	printf("Three: %d\n",num);
	
	enum custom c;
	c = con1;
	printf("%d\n",c);
	c = con2;
	printf("%d\n",c);
	c = con3;
	printf("%d\n",c);
	c = con4;
	printf("%d\n",c);
	c = con5;
	printf("%d\n",c);
	c = con6;
	printf("%d\n",c);
	
	return 0;
}

Output

Three: 3
100
101
102
1000
1001
1002

Trending

C Programming

Remember to follow community guidelines and don't go off topic.