Field Select Operators

There are two operators used for field selection in structures and unions. The first is the period, '.'. It is used with the name of the "struct" or "union" on the left and the name of the field on the right. See the following program fragment:

 
	struct complex {
		float real;
		float imag;
	} z1[3],z2,z3;
	...
	/* complex addition */
	z1[2].real=z2.real+z3.real;
	z1[2].imag=z2.imag+z3.imag;

The expression to the left of the period operator must be some kind of instance of a structure (or union) and the expression on the right must be a field of that structure. In the case of a union the field, or field name, on the right, tells the compiler which type from the union is to be used for the data in the union.

If instead of having a data object that is a structure, you have a pointer to a structure (or union):

	struct complex *pz=&z2;

then to use that pointer, there are two possibilities. One can use the indirection operator as follows:

	(*pz).real

And note that the parenthesis are needed else it means to dereference the pointer field 'real' of the structure 'pz'; i.e. it would interpret the field as a pointer - which it is not. Or, alternately, one can use the second operator,

    ->

which is used as an abbreviation for the above as follows:

	pz->real

This second way to to access fields with a structure or union pointer makes the notation much simpler especially when there are structure pointers within a structure pointing to structure pointers, etc.

	struct list {
		int value;
		struct list *next;
	} *a;
	...
	a->next->next->next->value

otherwise the more awkward:

	(*(*(*(*a).next).next).next).value

© 1991-2008 Prem Sobel. All Rights Reserved.