8.4. 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. Actually, it is possible to define the meaning of these operators for the new type, but we won’t do that in this book.

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 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 };

Before C++11 (2011), a cast was required for assignment. This form of assignment was written like the following. Both forms are supported in modern compilers.

Point blank;
blank = (Point){ 3.0, 4.0 };

It is legal to assign one structure to another. For example:

Point p1 = { 3.0, 4.0 };
Point p2 = p1;
cout << p2.x << ", " <<  p2.y << endl;

The output of this program is 3, 4.

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

You have attempted of activities on this page