struct – what are they for

A struct (structure) is a defined type that the user can define at compile time, for example if you want to have a user defined type that holds details of a database connection you could hold the hostname, username, password of the database connection within a structure (struct) without having to define 3 different variables you only have one that you need to fill in.

For the above example of a database struct

struct database_connection
{
   char *username;
   char *hostname;
   char *password;
};

then within the code you could create a new structure of this type and also fill in the details as

database_connection mydatabase;
mydatabase.username = "usernamebob";
mydatabase.hostname = "localhost";
mydatabase.password = "userpassword";

and you just need to pass that struct to a function if you wanted to to do the connections e.g.

bool dummyconnection(database_connection conn)
{
   createdatabase( conn.hostname, conn.username, conn.password);
}

saves passing in three different parameters.

Leave a Reply

Your email address will not be published. Required fields are marked *