The struct type is comparable to classes in object-oriented programming. Sometimes you may need to assign values to objects with the same properties. Instead of creating multiple variables for these objects in your C program, you can define them in a struct.

Creating a Struct

To define a structure, use the keyword struct, followed by the structure name. Inside the structure, you can specify variables of different types:

You can define several instances of Car by adding those instance declarations after the right brace in your struct declaration:

You can also nest a structure inside a structure. See the example below:

Operations on Struct Types

Initialization

There are three ways in which you can initialize the elements of a struct.

You can insert the comma-separated values in {} brackets & then assign them to the structure. You should note that the values must be in the same order that you declared the variables.

You can also assign the values without minding the order in which you declared them. See the example below.

The third way to initialize your struct is to assign it an existing structure of the same type.

Accessing Struct Elements

To access the value stored in a structure element, use the dot operator.

A Look at Object-Oriented Programming

As mentioned at the beginning, struct is comparable to using classes in object-oriented programming (OOP). Classes are simpler to use and enable code reuse.

For this reason and many others, C++ was introduced. C++ is the object-oriented version of C. Next on your reading list should be understanding the concepts in OOP.