Something about programming

Structures in C language

Previous tutorial: Pointers in C programming language
Next tutorial: Arrays and strings in C language

In previous tutorials we decided to make a pseudo-game there user controls the tank. We had three variables:

int x,y;
char letter;
float fuel;

x, y - coordinates, letter - representation of tank on the field (just a character) and amount of fuel. The problem here that if we want to add another tank to the game (enemy or another player), we need to create more variables. We can use the names: x1, y2, letter1 and fuel1. We need another tank? Another set of variables. Very quick we'll have a very bad code with lots of senseless variables.

C language structures will solve our problem. Structure allows to combine several variables in one entity.

struct

Firstly, we need to define the structure. There is a keyword for structures in C - struct. When we define the structure, it's like we create the blueprint and then from this blueprint we can create many entities that have similar characteristics. Let's define the structure for a tank in our game:

struct Tank {
   int x;
   int y;
   char letter;
   float fuel;
};

On first line there is a keyword struct, then the name of the structure. In braces we put all properties that each tank must have. These variables are called member variables. Of course in real life tanks has much more properties, but we are creating just the model - the representation of it in our game and we'll begin with four member variables in structure.

Now, when we defined the structure, we can create many structure variables.

struct Tank player;
struct Tank enemy;

player.x = 0;
player.y = 0;
player.letter = 'T';
player.fuel = 400;

enemy.x = 5;
enemy.y = 5;
enemy.letter = 'X';
enemy.fuel = 100;

Here is the interesting thing. When we created structure variables player and tank, we printed struct Tank as their data type. In some sense structures allow to create your own data type that combines variables of standard C data types.

In the code we address the inner variables of structure variable through dot operator. On the left side there is a name of structure variable, on the right side of dot there is a member variable.

Each structure variable has different member variables so player.x is not the same as enemy.x - this is very important.

Conclusion

Structures are quite easy to understand and I think you'll not have a problem with them.

Structures allows us to more easily model different objects of real word and we'll use them a lot.

Comments:

No comments yet