CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Defining our own datatypes

We can further simplify our code, and more clearly identify related data by defining our own datatypes.

Recall material from Lecture-6 where structures, and arrays of structures were introduced. We preceded each structure's name with the struct keyword, and accessed structure elements using the 'dot' operator.

Instead, we can use the typedef keyword to define our own new datatype in terms of an old (existing) datatype, and then not have to always provide the struct keyword:


//  DEFINE THE LIMITS ON PROGRAM'S DATA-STRUCTURES
#define MAX_TEAMS               24
#define MAX_TEAMNAME_LEN        30
....

typedef struct {
    char    teamname[MAX_TEAMNAME_LEN+1];        // +1 for null-byte        
    ....
    int     played;
    ....
} TEAM;

TEAM    team[MAX_TEAMS];

As a convention (but not a C11 requirement), we'll define our user-defined types using uppercase names:

//  PRINT EACH TEAM'S RESULTS, ONE-PER-LINE, IN NO SPECIFIC ORDER
for(int t=0 ; t<nteams ; ++t) {
    TEAM    *tp = &team[t];

    printf("%s %i %i %i %i %i %i %.2f %i\n", // %age to 2 decimal-places
            tp->teamname,
            tp->played, tp->won, tp->lost, tp->drawn,
            tp->bfor, tp->bagainst,
            (100.0 * tp->bfor / tp->bagainst),      // calculate percentage
            tp->points);
}

 


CITS2002 Systems Programming, Lecture 16, p3, 19th September 2023.