Skip to content

Type Declaration

When a new structure is created, we are actually declaring a new data type. They are called structure type.

Structure Type

Syntax

struct
1
2
3
4
5
6
typedef  struct {
  <data type> <member name>;
  <data type> <member name>;
  <data type> <member name>;
  :
} <struct name> ; // <-- the semi-colon is very important and often forgotten

Note that a type is NOT a variable. Remember, a variable has 4 attributes: name, type, address and value. By declaring a structure type using typedef, we are basically saying that there is this new type called <struct name>.

In particular, do note the following major differences:

  • A type needs to be defined before we can declare variable of that type.
  • No memory is allocated to a type.
    • Memory will only be allocated when a variable of that type is declared.

Structures

Bank Account

account_t
1
2
3
4
typedef struct {
  int acctNum;
  float balance;
} account_t;

Student Result

result_t
1
2
3
4
5
typedef struct {
  int stuNum;
  float score;
  char grade;
} result_t;

As a good practice, you should put any type declaration before function prototypes so that it can be used by the function prototype1. However, it should be after preprocessor directives so that you can use other types declared in a library if you are using #include. Additionally, you should also name the structure with a suffix _t at the end to indicate that this is a new type.

C Program Template with Structure

Template
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Preprocessor directives
// e.g.: #include #define

// Structure type declarations
// e.g.: typedef struct { ... } struct_name;

// Function prototypes
// e.g.: double circle_area(double); <-- ends with semi-colon

int main(void) {
  // Variable declarations
  // e.g.: int x

  // Inputs
  // Computations
  // Outputs

  return 0;
}

// Function definitions
// e.g.: double circle_area(double x) { return ...; } <-- note the function body

Array of Structures

Now that we have managed to create a structure for student results, we can combine this structure with array to create an array of structures. This will be particularly useful at the end of the semester when we have to submit the results of all students.

Since a structure creates a type, we can then create an array this type.

Array of Student Results
1
result_t all_results[SIZE];

Each of the element in the array variable all_results is of type result_t.


  1. Remember, C compiler is one-pass compiler. If the compiler have never seen the type before, it cannot be used.