Monday, January 26, 2009

Assignment Operators

An unusual feature of C is that the normal binary operators like `+', `-', etc. can be combined with the assignment operator `=' to form new assignment operators. For example,
x =- 10;
uses the assignment operator `=-' to decrement x by 10, and
x =& 0177
forms the AND of x and 0177. This convention is a useful notational shortcut, particularly if x is a complicated expression. The classic example is summing an array:
for( sum=i=0; i sum =+ array[i];
But the spaces around the operator are critical! For
x = -10;
sets x to -10, while
x =- 10;
subtracts 10 from x. When no space is present,
x=-10;
also decreases x by 10. This is quite contrary to the experience of most programmers. In particular, watch out for things like
c=*s++;
y=&x[0];
both of which are almost certainly not what you wanted. Newer versions of various compilers are courteous enough to warn you about the ambiguity.
Because all other operators in an expression are evaluated before the assignment operator, the order of evaluation should be watched carefully:
x = x<means ``shift x left y places, then OR with z, and store in x.'' But
x =<< y | z;
means ``shift x left by y|z places'', which is rather different.

No comments:

Post a Comment