In C/C++ keywords such as struct, union, enum and typedef allows you to create useful user-defined data types, such as structures.

As you know, the C language has some standard types such as int, double and char.

However you can create your own type, from the basic ones.

This feature is amazing!

There are four keywords that allows you to do this:

  • typedef ( Type definition )
  • struct ( Structure )
  • union ( Union )
  • enum ( Enumeration )

Typedef ( Type Definition )

Defining a type means giving a custom ID to an existing data type and it’s used only to improve the readability of a piece of code.

In fact, for example, it can be annoying to define a lot of variables of a modified data type with a long name, such as unsigned short int.

Instead, it’s a lot faster to give it a shorter name, such as hex.

You can also give a type another ID to know which purpose it serves.

For example, if I need some variables that take up only one byte, but they aren’t characters, I can define a new type called byte from the existing char, so that your coworker will understand better your code.

Now that you’ve understood what is the use of defining a type, let’s see how to do it.


This is the syntax of typedef, the keyword which fulfil this task:


  • typedef tells the machine that you’re defining a type.
  • old_ID is the name of an existing type.
  • new_ID is the name of your new type.

Piece of code with and without typedef

As you can see, the piece of code on the left has one more line, but it’s way easier to read.

Struct ( Structure )

A structure is a collection of variables.

The main difference between structures and arrays is that the first one can contain members of different types.

They are useful when, for example, you want to create a record with people’s data, such as name, age and date of birth.

Defining and managing all these variables for each person is harder than using a custom type that contains all this information in one place.


The keyword used to create a structure is struct. Let’s see its syntax:


  • struct tells the machine that you’re defining a structure.
  • struct_name is the name of your structure.
  • type1 var1; … are the variables that the new type contains. They can be even arrays or other user-defined data types.

All the members of a structure must be put inside curly brackets and you mustn’t use an equal sign.

Instead, you must use that sign if you’re initialising a structure.

Initialising a structure variable

The example above creates a type called Record which contains one string and four integers – Don’t use an equal sign when you’re defining a structure.

Then it define a variable rec1 of type Record and it initialise it – Use an equal sign when you’re initialising a structure.

Using typedef and struct together

Each time you want to use the ID of a structure, you have to write the keyword struct before it, but there’s a way to avoid this.

Using typedef you can give to a structure another ID that doesn’t require the struct keyword:

Where struct Rec{…} corresponds to old_ID, while Record to new_IDCheck the syntax of typedef above.

Anonymous structures

When you’re using struct and typedef together, you can also define an anonymous structure:

This is my favourite syntax.

You can define an anonymous structure only when you’re using it oncee.g. with typedef as old_ID or as nested structure.

Nested structures

Moreover, you can also define a structure inside a structure ( nested structure ).

Accessing the elements of a structure

In order to access the elements of a structure you have to use:

  • a dot ( structure.element ) if structure is a variable.
  • -> ( structure->element ) if structure is a pointer.
Example: Person Record

The following program sums up all the concepts you’ve learnt so far:

Structure example - coloured

 Output of the Structure Example

Union ( Unions )

Unions are collections of variables that occupies the same space in the computer memory.

At first it might seem difficult to understand, but actually the concept is quite simple.

Look at the image below that represent the following union:

Unions in the computer Memory

As you can see, integer, the biggest variable, takes up also the space occupied by character.

Modifying a variable of a union

If you assign a new value to one of the members of a union, it’ll overwrite the space dedicated to that variable.

For example: in the previous union, if you set the value of character to ‘A’ the last byte of integer will become 01000001.

If you set the value of integer to 41000, the value of character will be ‘(‘.

Defining a union variable

Defining a union variable is similar to defining a structure variable:

You can also use typedef to avoid repeating the keyword union:

Accessing the elements of a union

In order to access the elements of a union you have to use:

  • a dot ( un.element ) if un is a variable.
  • -> ( un->element ) if un is a pointer.
Example: Secret Code

Union Example

Result of the Union Example

How to calculate the index of a cell
To calculate the index of a cell of a table, multiply the index of the current row by the number of elements on that row and sum the result to the index of the current column.

index = row*Length+column

Enum ( Enumeration )

An enumeration is a user-defined data type that assigns a name to each integer value.

Basically, it contains an integer value with a fancy name.


In order to define an enumeration, you have to use the keyword enum:


The value of each member goes from 0 ( for the first one ) to n ( for the last one ), 6 in this case.

Defining an enum variable

Defining an enum variable is similar to defining a structure or union variable.

You can use typedef here, too.

Example: Today’s date

Enum Example

Result of the Enum Example

Let’s analyse today’s program

Today’s program is a good recap of everything you learnt so far.

It uses structures, unions, enumerations, conditions, loops, strings and more.

What does it do? It asks the user to compile a registration form with a bunch of information, such as name, age and date of birth.

typedef struct{ ... } Record

It defines a new structure type called Record, which contains:

  • A string, called name;
  • An integer, called age;
  • A structure, called birth;
  • Another integer, called UK_Citizen;
  • A union, called location;
  • An enum, called hair_colour.

Record new_user

This line creates a structure type variable.

Thanks to typedef we don’t have to repeat the struct keyword.

fgets(, 20, stdin)

It reads a line of maximum 20 characters from the command prompt and it assigns it to the member name of the structure new_user.

scanf("%d", &

You can access a member of a nested structure the same way you do for normal structures.


Sometimes a character get stuck in the input stream, causing the program to skip a scanf.

Using getchar you can read that character and free the stream.

To learn more about this topic, have a look at this post by G. Samaras.

if(answer=='Y' || answer=='y')

If the user answered ‘Y’ or ‘y’, he/she is a UK citizen.

do { ... } while(colour4)

This line ensures that the user entered a valid colour – a value between 1 and 4 ( included ).

new_user.hair_colour = colour-1

In C enum and int are compatible, so, through this line, the program assigns the user’s answer to the enumerated type variable of our structure.

Since I set colour to start from 1, but C starts counting from 0, it’s necessary to subtract 1 to the input.

do { ... }while(!(answer=='Q' || answer=='q'))

This loop repeats until the user enter ‘Q’ or ‘q’.

Translating today’s program to human language

Computer, this program uses the stdio.h library
Here’s the body of the program
Give to the following structure the name Record

A 20 elements array of characters, called name
An integer, called age
A structure variable, called birth, which contains:

three integers: day, month and year

Another integer, called UK_Citizen
A union type variable, called location, that contains:

two strings: nationality and city_of_birth

An enumerated type variable, called hair_colour, that can assume the following values:


Define a Record variable called new_user
Print “Registration Form:\n\n”
Print “First Name: ”
Read a maximum of 20 character from the current line of the command prompt and assign them to the name member of the variable new_user
Print “Age: ”
Read an integer and assign it to new_user’s age member
Print “Date of birth (d m y): “:
Read three integers and assign them to the members of the birth structure of new_user
Get a character, but discard it
Print “Are you a UK citizen? (Y/N): ”
Create a variable called answer
Read a character and assign it to answer
If answer is equal to Y or y, do the following:

Set the value of new_user’s UK_Citizen to true ( 1 )
Print “Where were you born? ”
Read a maximum of 20 character from the current line of the command prompt and assign them to new_user’s location’s nationality variable


Set the value of new_user’s UK_Citizen to false ( 0 )
Print “Where are you from? ”
Read a maximum of 20 character from the current line of the command prompt and assign them to new_user’s location’s city_of_birth variable

Create an integer called colour

Print “Which colour is your hair?\n1: BROWN\n2: BLACK\n3: BLOND\n4: OTHER\nAnswer: ”
Read an integer and assign it to colour

…Until colour is less than 1 or greater than 4
Assign colour-1 to the hair_colour variable of new_user
Print “\nCheck your data:\n\n”
Print the information contained in new_user

Get a character, but discard it
Print “Enter Q to quit: ”
Read a character and assign it to answer

…Until answer isn’t equal to ‘Q’ or ‘q’

C and C++ comparison

There are three differences I want to point out:

  1. Enum and int aren’t compatible in C++, therefore I defined an enumerated type Hair outside the structure so that I can cast the int I want to assign to the new type, writing (Hair) variable
  2. fgets() becomes cin.getline() in C++
  3. getchar() becomes cin.get() in C++


Once having read this long post you’ve learnt how to define and use structures, unions, enumerations and how to give new IDs to an existing type.

You learnt how to create a record, an encryption program and a registration form.

In the next weeks, we will also see how to save the information you can get through the registration form we made previously and how to send encrypted codes to friends.

You can subscribe to my newsletter – you find it at the side of the page on computer or on the Home Page – to never miss any update.

If there’s something you want to ask me, feel free to do it through a comment below.

Otherwise, if you think that this post might help a friend of yours, share it!

Anyway, the post is finished, have a good day and we will see next week!

From Zephyro it’s all, Bye!

Categories: Learn C

Leave a Reply

%d bloggers like this: