Enums, Structures and Unions


1. Linux Distribution (obviously)
2.A text editor :
Vim, Emacs, gedit, kate, atom
3.A Compiler :
gcc or clang
A Shell:
bash, xterm, sh,


My setup for this tutorial:

1. Debian GNU/Linux 9.4
2. Atom (Text editor)
3. gcc version 6.3.0-18+deb9u1 (Debian’s Release version for Debian 9.1)
4. bash


Now that you understand the basics and primitive types of C, we will go over the more interesting features of the language.


Enumerations are data types which provide named data to variables. In C, they are treated as integers. You can define them as such:

     enum dayOfWeek{
           sunday = 1,

This declares an enumeration of data starting with number 1. Each value after is incremented, so monday = 2 , tuesday = 3, etc. You would then declare a variable of that enum as such:

     enum dayOfWeek today;

You can assign this with either:

     today = sunday;
    today = 1;



Structures are a way to pack multiple data types into one. They are the size of every single data type that they contain. It is used to group data together. Say you needed to store information for a window application. A Possible idea would be:

typedef struct {
const char * name;
int height;
int width;


This is one of the ways you can define a structure. It is one of my favorite ways due to its simplicity. This now allows me to use the structure name as a variable type itself as such:

window_t myWindow;

Other ways include just defining the struct itself as such:

struct window{
const char * name;
int height;
int width;

Now if you do this, when declaring a variable of window, you would use:

     struct window myWindow;

The reason being is that in the first example, we use the typedef keyword to tell the compiler to define a type of struct , with those member variables , with the name of window_t. In the second example, we just tell the compiler there is a POD (Plain-old-data) type window. In C when dealing with enums, Structures and Unions, you normally have to write out the type you are specifically stating, as you have noticed when we used the day of week enumeration, we first typed enum, and the second example of window that i showed you. Using the typedef keyword allows you define new types of data based off of older types.

//typedef     #OLD       #NEW
typedef   struct window myWindow;



Unions are an interesting feature in C. It is like a structure, but its size is the size of the biggest data type within the union. Say you have :

     typedef union {
          int asInt;
          float asFloat;

     myUnion u;
     u.asInt = 15;
     u.asFloat = 3.14f;

     prinf("U:\nasInt= %d\nasFloat= %f\n",u.asInt,u.asFloat);

Notice, you will see asInt will be a garbage value after 3.14f is assigned to it. It stores everything thats in the data type in one spot in memory, it is assigned the size of the biggest data type within it. These are a more advanced concept and I would suggest researching about these on your own.

Leave a Reply