Breaking Down Structures

In the C language, struct is a variable type, but do you declare a structure or define a structure? That one has me perplexed.

Regardless of the nomenclature, a structure is a collection of variable types, like a record in a database. You can pack any type of variable into a structure — including more structures. The idea is that the information within the structure is related and somehow serves a useful purpose by being referenced as a unit.

A simple example is a structure that holds a date value:

struct date {
    int year;
    int month;
    int day;
};

The structure is named date. It holds three members (not elements), all int variables.

Defining a structure doesn’t create a structure variable. It merely tells the compiler, “Hey! Here’s a new type of structure. Maybe I’ll use it.” To declare a structure variable, you use this format:

struct date birthday;

The variable birthday uses the date structure type. It’s assumed that the date structure is defined elsewhere.

Here’s sample code:

#include <stdio.h>

int main()
{
    struct date {
        int year;
        int month;
        int day;
    };
    struct date birthday;

    birthday.year = 1935;
    birthday.month = 7;
    birthday.day = 6;

    printf("The Dalai Lama was born on %d/%02d/%d.\n",
            birthday.month,
            birthday.day,
            birthday.year);

    return(0);
}

To access a structures members, you use the structure variable name (not the structure name). So the sample code uses birthday not date. Then you use a dot and the structure member name.

Here’s sample output:

The Dalai Lama was born on 7/06/1935.

Hopefully all this info is familiar to you if you’ve read my books. If not, it always helps to brush up.

One thing other programmers do that I don’t is combine the structure definition and the variable declaration into a single statement. It looks like this:

struct date {
    int year;
    int month;
    int day;
} birthday;

This statement (it’s one statement split over 5 lines) both defines the date structure and declares a date structure variable, birthday. You may prefer this method, which is fine. I expand it out to two statements, which does the same thing but it makes structures easier to teach.

For me, the most difficult part of using structures is coming up with clever names: one for the structure itself and another for the structure variable. Generally speaking, I can come up with a single clever name for either the structure or the variable, but not both. I’ll continue to work on that.

In next week’s Lesson, I’ll review nested structures.