Skip to main content

Section 15.3 Operations on structures

Most of the operators we have been using on other types, like mathematical operators ( +, %, etc.) and comparison operators (==, >, etc.), do not work on structures. (It is possible to define custom operators, but we won’t worry about that yet.)
On the other hand, the assignment operator does work for structures. It can be used in two ways: to initialize the instance variables of a structure from a list of values or to copy the instance variables from one structure to another. An initialization looks like this:
Point blank = { 3.0, 4.0 };
The values in squiggly braces get assigned to the instance variables of the structure one by one, in order. So in this case, x gets the first value and y gets the second.
This syntax can also be used in an assignment statement. So the following is legal.
Point blank;
blank = { 3.0, 4.0 };
The second use of assignment is to copy one struct into another:
Point p1 = { 3.0, 4.0 };
Point p2 = p1;
It is important to note that an assignment makes a copy of a struct. Once the assignment has been made, changing one struct has no effect on the other. This Codelens demonstrates by coping a struct and then changing one of the copies.
Listing 15.3.1.

Checkpoint 15.3.1.

Construct a block of code that correctly initializes the instance variables of a structure.

Checkpoint 15.3.2.

Which operators do NOT work on structures. Select all that apply.
  • The modulo operator does not work on structures.
  • The assignment operator does work on structures.
  • The greater than operator does not work on structures.
  • The equality operator does not work on structures.
  • The addition operator does not work on structures.
You have attempted of activities on this page.