17 Jul C – Enums
We studied some types in C. However, there is another type in C programming called Enums. Enums, stand for enumerations i.e., a group of constants. Use enums to name constants.
In C, we use the enum keyword to create an enum. Let us see the syntax:
1 2 3 4 5 6 7 8 9 10 11 |
enum enum_name { enum_item1, enum_item2, enum_item3, . . . enum_itemn }; |
Above, we have the enum name after the enum keyword. Then comes the enum items separated by comma.
Create an Enum
Let us now see how to create an enum. We will consider Directions and enum items as NORTH, SOUTH, etc:
1 2 3 4 5 6 7 8 |
enum Directions { NORTH, SOUTH, EAST, WEST } |
Create an Enum Variable
Create a variable of the Enum if you want to access it. Let us create a variable of the above enum:
1 2 3 |
enum Directions d1; |
Assign a value to the enum variable
On assigning a value to the enum, the resultant value will display an increment based on the enum items i.e.:
Let us now assign value to the enum items and display:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> enum Directions { NORTH, SOUTH, EAST, WEST }; int main() { // Create Enum variables enum Directions d1, d2; // Assign value to the Enum variable d1 d1 = NORTH; printf("%d\n", d1); // Assign value to the Enum variable d2 d2 = SOUTH; printf("%d", d2); return 0; } |
Output
1 2 3 4 |
0 1 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments