We may not have the course you’re looking for. If you enquire or give us a call on +34 932716793 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Are you looking for a way to enhance code clarity in your C programs? Discover how Enums in C can transform your coding experience. Enums, or Enumerated types, are custom data types that consist of named integer constants. They allow developers to group related values under meaningful names, improving readability and making the code easier to maintain. Explore the benefits of using Enums in C to simplify your code and enhance your programming skills today!
Table of Contents
1) What is Enumeration (or Enum) in C?
2) How to Utilise Enum in C?
3) Syntax for Defining Enum in C Language
4) Defining and Declaring an Enum Type
5) Using Enum in Switch Statements
6) Declaring Enum Variables
7) Modifying Enum Constant Values
8) Examples of Enumerations (Enum)
9) Enum in C vs Macro: Key Differences
10) Conclusion
What is Enumeration (or Enum) in C?
An Enum (short for “enumeration”) in C is a user-defined data type that consists of a set of named integer constants. This feature is particularly useful for representing a collection of related values in a more readable and maintainable way. Here’s a deeper look into enums:
Enums are defined using the Enum keyword followed by a name and a list of named integer constants enclosed in curly braces.
How to Utilise Enum in C?
Enums in C are used as constants or when a variable needs a specific set of values. For example, a weekdays Enum has seven values, one for each day of the week. However, a variable can only hold one of these values at a time. Enums in C have several uses:
a) Storing Constant Values (e.g., weekdays, months, directions, rainbow colours)
b) Using Flags
c) Enhancing Switch-case Statements
Enums provide a clear and organised way to handle related constants.
Syntax for Defining Enum in C Language
In C, you define an Enum using the Enum keyword, with constants separated by commas. The syntax is:
enum enum_name {int_const1, int_const2, int_const3, ..., int_constN}; |
By default, int_const1 is 0, int_const2 is 1, int_const3 is 2, and so on. You can change these default values. Here’s an example of an Enum named fruits and how to modify the default values:
enum fruits {mango, apple, strawberry, papaya}; |
To change the default values:
enum fruits { Kiwi = 20, banana = 10, strawberry = 5, Orange = 7, }; |
This sets Kiwi to 20, banana to 10, strawberry to 5, and Orange to 7.
Boost your career with our C programming Training. Learn from professionals, master coding techniques, and gain valuable skills to excel in the tech industry. Start learning today!
Defining and Declaring an Enum Type
To declare and define an Enumeration data type, use the Enum keyword followed by the name of the Enum. List all the values within curly braces.
Syntax
Here’s the syntax for defining an Enum type:
enum enum_name {const1, const2, ... }; |
Using Enum in Switch Statements
The switch case statement in C works with integral values. You can use the Enum type to define constants, which can be used in switch case statements, whether or not they have integral values. The following example Enumerates the colours of the rainbow:
#include // Enum declaration enum colors { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED }; int main() { // Enum variable declaration enum colors color = YELLOW; // Switch statement using enum switch (color) { case BLUE: printf("Blue color"); break; case GREEN: printf("Green color"); break; case RED: printf("Red color"); break; default: printf("Color other than RGB"); } return 0; } |
When you run the code, you will see the output:
Color other than RGB |
Declaring Enum Variables
A common use of Enumerated data types is to assign integer values to the days of the week. In this code, we declare a variable of the weekdays Enum type:
#include enum weekdays { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; int main() { enum weekdays day; day = Wed; printf("Day number of Wed is = %d", day); return 0; } |
When you run this code, the output will be:
Day number of Wed is = 3 |
Modifying Enum Constant Values
When we declare an Enum type, the first constant is automatically initialised to 0 by default, the second to 1, and so on. We can also assign specific integer values to any Enum constant.
In this example, we declare an Enum type and assign different values to the constants:
#include enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 }; int main() { // Printing values printf("OKAY = %dn", OKAY); printf("CANCEL = %dn", CANCEL); printf("ALERT = %dn", ALERT); return 0; } |
When you run this code, the output will be:
OKAY = 1 CANCEL = 0 ALERT = 2 |
Boost your programming skills with the C Programming Course. Join our beginner-friendly course and start coding confidently!
Examples of Enumerations (Enum)
Practice the following examples to understand the concept of Enumerated types (Enums) in the C programming language.
Example 1: Enum Constants Get Incrementing Integer Values
In C, each constant in an Enum is assigned an incrementing integer value, starting with 0. For example, when we assign val2 to a variable, the integer value for val2 is 1. Here’s an example:
#include enum myenum { val1, val2, val3, val4 }; int main() { enum myenum var; var = val2; printf("var = %d", var); return 0; } |
When you run this code, it will produce:
var = 1 |
Example 2: Enumerating the Weekdays
We can declare an Enum type called weekdays to list the days of the week. Here’s how to assign values to the Enum constants:
#include int main() { enum weekdays { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; printf("Monday = %dn", Mon); printf("Thursday = %dn", Thu); printf("Sunday = %dn", Sun); } |
Running this code will give the following output:
Monday = 1 Thursday = 4 Sunday = 0 |
Example 3: Declaring a Variable of Enum Type
Enums can also be used to assign integer values to weekdays. Here is a code example:
#include enum weekdays { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; int main() { enum weekdays day; day = Wed; printf("Day number of Wed is = %d", day); return 0; } |
When you run this code, you will see:
Day number of Wed is = 3 |
Example 4: Enum Values by Default Start from 0
In this example, we define an Enum for the names of the months in a calendar year. By default, C assigns values starting from 0. For instance, January gets 0, February gets 1, and so on.
#include enum months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; int main() { for (int i = Jan; i <= Dec; i++) printf("Month No: %dn", i); return 0; } |
Run the code and you will see:
Month No: 0 Month No: 1 Month No: 2 Month No: 3 Month No: 4 Month No: 5 Month No: 6 Month No: 7 Month No: 8 Month No: 9 Month No: 10 Month No: 11 |
Get started with Embedded C concepts today- join our Introduction of Embedded C Programming Course today!
Example 5: Starting an Enum from 1
To start the Enumeration from 1, you can explicitly assign the first value to 1. The compiler will then assign incrementing numbers to the following values.
#include enum months { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; int main() { for (int i = Jan; i <= Dec; i++) printf("Month No: %dn", i); return 0; } |
When you run this code, the output will be:
Month No: 1 Month No: 2 Month No: 3 Month No: 4 Month No: 5 Month No: 6 Month No: 7 Month No: 8 Month No: 9 Month No: 10 Month No: 11 Month No: 12 |
Example 6: Enumerating HTTP Status Codes
Enum constants do not have to be assigned incremental integer values. You can assign unique values to each constant in any sequence. Here is an example using HTTP status codes:
#include enum status { OK = 200, BadRequest = 400, Unauthorized = 401, Forbidden = 403, NotFound = 404, InternalServerError = 500, }; int main() { enum status code = InternalServerError; if (code == 500) printf("Internal Server Error has been encountered"); return 0; } |
Run the code to see:
Internal Server Error has been encountered |
Example 7: Assigning a Fixed Number to Enum Constants
You can assign specific integers to some constants while allowing the compiler to assign values to others. Unassigned names will get a value that is one greater than the previous name.
#include enum myenum { a, b = 5, c, d, e = 10, f }; int main() { printf("a: %dn", a); printf("b: %dn", b); printf("c: %dn", c); printf("d: %dn", d); printf("e: %dn", e); printf("f: %dn", f); return 0; } |
When you run this code, the output will be:
a: 0 b: 5 c: 6 d: 7 e: 10 f: 11 |
Enum in C vs Macro: Key Differences
In C, both Enums and Macros can be used to define named constants, but Enums offer several advantages over macros. Here are the key differences:
1) Scope Adherence
a) Enum: Enums follow scope rules, meaning their values are confined to the scope in which they are defined.
b) Macro: Macros do not follow scope rules, which can lead to name conflicts if not carefully managed.
2) Type Safety
a) Enum: Enums provide type safety, ensuring that only valid values are assigned to variables of the Enum type.
b) Macro: Macros do not provide type safety, which can lead to unintended behaviour if incorrect values are used.
3) Automatic Value Assignment
a) Enum: The compiler can automatically assign values to Enum items, making the declaration simpler and less error-prone.
b) Macro: Values must be manually assigned, which can be more cumbersome and prone to errors.
4) Debugging and Readability
a) Enum: Enums improve code readability and make debugging easier, as the names of the Enum constants appear in the debugger.
b) Macro: Macros are replaced by their values during preprocessing, which can make debugging more difficult.
5) Maintenance
a) Enum: Enums are easier to maintain, as changes to the Enum list are automatically reflected wherever the Enum is used.
b) Macro: Changes to macros require manual updates in all places where the macro is used.
Using Enums in C is generally recommended for defining named constants due to these benefits.
Conclusion
Enums in C are useful for defining related constants. They make the code easier to read and maintain. By grouping integer values with meaningful names, Enums help developers write clearer code. Learning how to use Enums in C can improve your programming skills and code organisation.
Kickstart your career in Software Development with our C# Programming (C Sharp) – Register now!
Frequently Asked Questions
Enums allow you to define a collection of named constants, enhancing code readability and maintainability. Unlike arrays, Enums ensure that only valid values are used, reducing errors and improving type safety.
Yes, Enums make code more readable by replacing magic numbers or strings with meaningful names. This enhances code clarity, making it simpler to grasp the purpose of each value.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 19 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various C Programming Courses, including C Programming Training, C# Programming (C Sharp) Training and C++ Programming (C Plus Plus) Training. These courses cater to different skill levels, providing comprehensive insights into Types of Data Structures.
Our Programming & DevOps Blogs cover a range of topics related to C Programming, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your skills in C Programming, The Knowledge Academy's diverse courses and informative blogs have you covered.