Fundamental C - Enumerations
Written by Harry Fairhead   
Monday, 06 April 2020

This extract, from my new book on programming C in an IoT context, explains what enumerations are all about. You don't need them, but they do make your programs easier to read and hence perhaps less error prone.

This extract is from Chapter 8: Arrays, which concludes by considering the interaction between arrays and enumerations.

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays
      Extract  Ennumerations
  9. Strings
      Extract  Simple Strings
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

Cbookcover

 

In the chapter but not included in this extract:

  • The Array
  • Arrays and For Loops
  • Assigning Arrays - Pointers
  • Multi-Dimensional Arrays
  • Arrays as Parameters
  • Arrays and Return
  • The Problem of Size

Enumerations

One of the standard uses of an array is to store data relating to specific labels. For example, suppose you wanted to record the number of hours you worked in a week. You might want to write something like:

work[mon]=9;

C enumerations were designed to allow you to do exactly this and similar tasks. Notice first that the basic way to do this job would be to assign integers to days, Sunday=0 and so on.

So:

work[mon]=9;

would be:

work[1]=9;

An enumeration is just an assignment of integers to labels.

For example:

enum week {
 sunday=0, monday=1, tuesday=2, wednesday=3,
thursday=4,friday=5,saturday=6 }

This declares a new data type – enum week. In fact you don’t need to list the values because if you leave them out the compiler assumes you mean values from 0 increasing by one to however many values you need. In other words you could have written the above as:

enum week {
 sunday, monday, tuesday, wednesday, thursday,friday,
saturday }

If you do use explicit assignment then you can assign any integer values you like, i.e. they don’t have to be in order.

You can use this to create a variable that can only take on the values you have listed.

For example:

enum week work;

now you can write

work=monday;

Notice that monday is not a variable. The compiler looks up monday in your definition of the enum and replaces it by the integer you set it to. However work is a variable and it is just a plain old int.

In other words:

enum week work;
work=monday;

is converted to:

int work;
work=1;

which you can check with:

printf(“%d”,work);

which prints 1.

Notice that as monday isn’t a variable and it isn’t an lvalue you can’t assign to it and:

monday=9;

generates an error.

To return the original example, recording work hours for each day of the week. This can be done by declaring an array of type enum week:

enum week work[7];

Now you can write:

work[monday]=9;

Notice that work is an array of int and the compiler converts the instruction into:

int work[7];
work[1]=9;

You can also write things like:

for(enum week day=sunday;day<=saturday;day++){
   printf("%d\n",work[day]);
}

But it is worth keeping in mind that the compiler converts this into:

for(int day=0;day<=6;day++){
   printf("%d\n",work[day]);
}

In other languages this sort of transformation would be called “syntactic sugar” to indicate that it wasn’t a real addition to the language, just something that makes it more readable. This is about the only syntactic sugar C provides.

You can use enumerations in other contexts than arrays and for loops. One particularly common use is to implement options that can be combined using bitwise logical operators – see Chapter 12.

Another is to define what looks like a boolean type using:

enum bool {false,true};

After this you can declare a variable that appears to be a boolean. For example:

enum bool myBool;
myBool=true;
if(myBool) …

Notice that this myBool is still an int and true is 1 and false is 0.

In Chapter 11 we meet the typedef statement which can be used to define synonyms for types. Using this we can get rid of the need to use enum in all declarations. For example:

typedef enum {false,true} bool;

bool myBool=true;
if(myBool)…

Although this sort of approach is commonly used it can become confusing and lead to errors. If you can’t work with C99 and bool it is better to explicitly use ints and 0 and 1 for false and true.

Summary

  • The array is the most fundamental of the simple data structures and it is declared using type name[number of elements].

  • In C all arrays start from zero e.g. myArray[0] is the first element.

  • Array sizes in C are best regarded as fixed. C99 allows variable length arrays, but these are best avoided if at all possible.

  • You can initialize arrays at compile time using a list of comma separated constants in parentheses.

  • Arrays and for loops are a natural fit. The index in a for loop is often used to access particular array elements.

  • Often you have to work out an arithmetic expression involving the index that will give you the array elements that you need.

  • The variable that is created when you declare an array is a pointer to the first element of the array.

  • When you assign one array variable to another, value assignment applies, but the value copied is a pointer, i.e. a reference to the first element of the array, and this results in reference semantics.

  • Multi-dimensional arrays are created using the same array mechanism, but in this case creating arrays of arrays and so on.

  • Arrays can be passed as arguments to functions, but what is passed is a pointer to the first element.

  • You can return an array from a function, but in most cases this isn’t necessary. Returning an array that has been created within the function is also not a good idea because the local variable that references it will be destroyed when the function exits.

  • Finding the size of an array is a compile time operation in C before C99.

  • Enumerations can make working with arrays seem easier, but they introduce no new features to C.

Related Articles

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays
      Extract  Ennumerations
  9. Strings
      Extract  Simple Strings
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Ilya Sutskever Raise $1 Billion To Research Safe AI
11/09/2024

Safe Superintelligence, the company co-founded by Ilya Sutskever after he resigned from Open AI, has raised $1billion in cash funding, despite the fact that it intends not to release any products [ ... ]



Pulumi Envisions The Intelligent Cloud
18/09/2024

Today at PulumiUp, its 4th annual conference, Pulumi is announcing "Intelligent Cloud", its vision for AI-powered cloud infrastructure, and two new products, ESC GA and Insights 2.0.  


More News

kotlin book

 

Comments




or email your comment to: comments@i-programmer.info

 

Last Updated ( Monday, 15 June 2020 )