Overview
In addition to the simple data types (int, char, double, ...) there
are composite data types which combine more than one data element.
- Arrays are used to store many data elements of
the same type. An element is accessed by subscript, eg,
a[i].
- Structs (also called records) group elements which don't
need to all be the same type. They are accessed using the "." operator,
eg,
r.name.
- Classes are like structs where the members are private by default.
Use classes for object-oriented programming where
functions are defined in addition to the data members.
If there are only data members and no functions,
it is common to use structs instead of classes.
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