section 2.10: Assignment Operators and Expressions

page 50

You may wonder what it means to say that ``expr1 is computed only once'' since in an assignment like

	i = i + 2
we don't ``evaluate'' the i on the left hand side of the = at all, we assign to it. The distinction becomes important, however, when the left hand side (expr1) is more complicated than a simple variable. For example, we could add 2 to each of the n cells of an array a with code like
	int i = 0;
	while(i < n)
		a[i++] += 2;
If we tried to use the expanded form, we'd get
	int i = 0;
	while(i < n)
		a[i++] = a[i++] + 2;
and by trying to increment i twice within the same expression we'd get (as we'll see) undesired, unpredictable, and in fact undefined results. (Of course, a more natural form of this loop would be
	for(i = 0; i < n; i++)
		a[i] += 2;
and with the increment of i moved out of the array subscript, it wouldn't matter so much whether we used a[i] += 2 or a[i] = a[i] + 2.)

page 51

To make the point more clear, the ``complicated expression'' without using += would look like

	yyval[yypv[p3+p4] + yypv[p1+p2]] = yyval[yypv[p3+p4] + yypv[p1+p2]] + 2
(What's going on here is that the subexpression yypv[p3+p4] + yypv[p1+p2] is being used as a subscript to determine which cell of the yyval array to increment by 2.)

The sentence on p. 51 that includes the words ``the assignment statement has a value'' is a bit misleading: an assignment is really an expression in C. Like any expression, it has a value, and it can therefore participate as a subexpression in a larger expression. (If the distinction between the terms ``statement'' and ``expression'' seems vague, don't worry; we'll start talking about statements in the next chapter.)


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback