Physics and Astronomy
Home Our Teaching Resources C programming Appendix: some more details
Contents

# Appendix: Some minor points about structures and typedef.

The occasional appendices and optional examples in this module are for advanced material that you will not need for this module. They are intended for enthusiastic students who are interested in going further in programming for its own sake.

## Definition and declaration can be combined.

It's possible, although extremely rare, to combine the definition and declaration together. Here we define a structure type and declare an actual structure, mystruct:

int main() {
struct somestruct {
int j;
float x;
} mystruct;

// More stuff here..
(Note no word "typedef").

## Structures can be initialised at declaration

So to continue the previous example we may declare another structure and initialise it:

struct somestruct yourstruct = { 3, 4.5 };

## Any declaration can be made into a typedef

Sharp-eyed readers may have noticed that our example typical structure typedef in the main notes:

#define MAXLEN 64
typedef struct nuclide {
char name[MAXLEN];
double halflife;
} Nuclide;

has exactly the same form as the combined struction definition above, with the word "typedef" before it. This is a general rule: we may take any valid variable declaration and put the word "typedef" in front of it. When we do this we are not declaring a new variable but a new alias.

### Examples

Example Meaning
typedef double Float; Float is now an alias for double
Float y; y is a double

Example Meaning
typedef double coord[3]; coord is an alias for an array of three doubles
coord x; x is an array of three doubles
x[1] = 1.7; Typical use of the array x

Example Meaning
typedef double pos_t; Float is now an alias for double
typedef pos_t Position[3]; Position is an alias for an array of three Floats, i.e. three doubles
Position z; z is an array of three doubles
z[0] = 4.15; Typical use of the array z