C++ Notes: Structs

Overview

In addition to the simple data types (int, char, double, ...) there are composite data types which combine more than one data element.

Struct Declaration defines a new Type

Let's take an example of representing information about some products.
struct Product {
  char mfg_id[4];    // 4 char code for the manufacturer.
  char prod_id[8];   // 8-char code for the product
  int  price;        // price of the product in dollars.
  int  qty_on_hand;  // quantity on hand in inventory
};
This defines a new type, Product. The order of the fields is generally not important. Don't forget the semicolon after the right brace. The convention is to capitalize the first letter in any new type name.

Declaring struct variables

The new struct type can now be used to declare variables. For example,
Product widget;

Accessing the fields of a struct

Access the fields of a struct by using the "." operator followed by the name of the field.
widget.price = 200;
widget.qty_on_hand = 17;
strcpy(widget.mfg_id, "IBM");
strcpy(widget.prod_id, "Thingee");<>

Operations on structs

A struct variable can be assigned to/from, passed as a parameter, returned by function, used as an element in an array, .... You may not compare structs, but must compare individual fields. The arithmetic operators also don't work with structs. And the I/O operators >> and << do not work for structs; you must read/write the fields individually.

Like database records

Structs are like database records - a row in a table, where the field names are like the column names.

Related Pages

Struct example