Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 8: Creating and Using Enumerations

The real world is complicated – far more complicated than just whole numbers, numbers with fractions, Boolean values, and characters. In order to model it, C provides various mechanisms for custom and complex data types. For the next eight chapters, we are going to explore various ways that our intrinsic data types can be extended and combined to more closely match the real world.

The first of these extensible data types is enumerated types. These are named values that are grouped because of some conceptual relationship we want to give them; we don't really care about their values – we differentiate each item in the group by its name. There is a value corresponding to each name, but usually, although not always, that value is irrelevant to us; the significance lies in its unique name within the group of enumerated items. However, a specific value for each item in the group can be specified by us otherwise it will be automatically...

Technical requirements

As detailed in the Technical requirements section of Chapter 1, Running Hello, World!, continue to use the tools you have chosen.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter08.

Introducing enumerations

There are times when we want a program or function variable to take an integer value that is from a set of related values. For convenience, and to make the relationship between each value clear, each value in the set of values is given a name. We can think of this set as a grouping of conceptually related values.

Let's say we want a variable to represent the suits of a deck of cards. Naturally, we know each suit by its name – spades, hearts, clubs, and diamonds. But C doesn't know about card names or card suits. If we wanted to represent each of these suits with a value, we could pick any value for each, say, 4 for spades, 3 for hearts, 2 for diamonds, and 1 for clubs. Our program, using this simple scheme, might look as follows:

int card;
...
card = 3; // Heart.

But we would have to do the work of remembering the conceptual relationship. We would have to do the work remembering which value corresponds to which suit. This is...

The switch()… statement revisited

The switch()… statement is best used when we have a single value that can only have a specified set of values. Doesn't that sound like an enumerated type? It should and, happily, it does.

Using the switch()… statement to evaluate an enumerated type simplifies the intent of our code and helps to prevent some troublesome situations. Here is the shapeFunc() function revisited using the switch()… statement:

enum result_code shapeFunc( enum shape aShape)  {
  ...
  switch( aShape )
  { 
    case triangle: 
      ...
      break;
    case rectangle:
      ...
      break;
    case circle:
      ...
      break...

Using enumerated item values as literal integer constants

There is one other form of enumerated types. It is when we want to give an identifier to a literal constant value and we want to avoid the use of #define. Early versions of C relied upon the preprocessor heavily – later versions, much less so. The pros and cons of using the preprocessor will be discussed in Chapter 24, Working with Multi-File Programs.

Instead of using #define, we can declare an anonymous enumerated type that contains enumerated items that act identically to literal constants, as follows:

enum {
  inchesPerFoot = 12,
  FeetPerYard   = 3,
  feetPerMile   = 5280,
  yardsPerMile  = 1760,
  ...
}

Note that there is no name associated with the enum type; this is what makes it anonymous. Each of these enumerated values can be used wherever we need that value; we simply use its name. This will...

Summary

An enumerated type is a set of conceptually related named values. An enumerated item in an enumerated type is a way to give a name to a literal value. The value of an enumerated item is constant. Most of the time, the values are not significant, but items that are in the set themselves add meaning to the type. We can use enumerated types to create natural collections or groups of values, as we have seen with card suits and shapes. The switch()… statement is ideally suited to select and process items within an enumerated type. We can also use an anonymous enumerated type to name unrelated literal integer values instead of using #define for them.

An enumerated type, unfortunately, doesn't provide everything we might need to model the real world. For instance, in a deck of cards, each card has both a suit and a face value, two different enumerations. To combine them into a single card object that represents reality more closely, we need another custom data type...

Questions

  1. Why might you want to use an enumerated type?
  2. Do you have to give each enumerated constant a value?
  3. Do enumerated constants have to be unique with a group?
  4. Do the values of each case: condition in a switch()… statement have to be unique?
  5. Enumerated constants are limited to which intrinsic data type?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay