www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 11: Structures

Declaring Structures

by John Kopp

Support this site at no cost to you

A structure provides a means of grouping variables under a single name for easier handling and identification. Complex hierarchies can be created by nesting structures. Structures may be copied to and assigned. They are also useful in passing groups of logically related data into functions.

Declaring Structures
A structure is declared by using the keyword struct followed by an optional structure tag followed by the body of the structure. The variables or members of the structure are declared within the body. Here is an example of a structure that would be useful in representing the Cartesian coordinates of a point on a computer screen, that is, the pixel position.

struct point {
    int x;
    int y;
};

The struct declaration is a user defined data type. Variables of type point may be declared similarly to the way variables of a built in type are declared.

struct point {
    int x;
    int y;
} upperLeft;

is analogous to

float rate;

The structure tag provides a shorthand way of declaring structures.

struct point {
    int x;
    int y;
};

struct point left,right;
struct point origin;

The C language allows data types to be named using the keyword typedef. For example:

typedef double Money;
typedef unsigned long int ulong;

Money paycheck;
    /* This declares paycheck to be of type Money, or double */
ulong IDnumber;
    /* This declared IDnumber to be of type ulong, or unsigned long */

User defined data types such as struct may also be named using typedef.

typedef struct point {
    int x;
    int y;
} Dot;

Dot left,right;
    /* Declares left and right to be Dots, or structures of type point */

The examples in the next section will present the different ways of declaring structures.

Previous Page       Next Page