C++ Structures

A structure is a collection of related elements enclosed under a single name. Structures are a way of storing many different variables and data of different types under the same name. Arrays are similar to structures, in that large amounts of data can be stored under one name. However, arrays can hold data of only one type, whereas structures can hold data of many types.

To declare a structure type in C++, you use the keyword struct, followed by the structure name. Next, you declare the list of field names. The field names are declared in the same way as you would declare a list of variables. The syntax of a structure declaration is given below.

struct type-name 
{
   type1 fieldName1;
   type2 fieldName2;
   ...

   typen fieldNamen;
};

To create an instance of your defined structure, use: type-name structure-name;

Structures are most commonly used in databases. If you are familiar with databases, you will know that a field is the smallest element used to store meaningful data. These fields become treated just like regular variables: they can be assigned values, which in turn can be accessed for selection or manipulation. A collection of these fields is known as a record, and you can think of the structure type as a record.

Because fields are like variables, you can perform the same assignment statements just like regular variables. To do this, you type: structure-name.fieldName

An example of a program using structures is given here.


This page has been accessed     times.
Last modified: Friday, 21-Aug-2020 15:28:14 CST
Copyright 2000 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material