Increment/decrement operators in C
Wirth supposedly considered p++ as a legacy mistake. Be that as it may, I am inclined to agree. Mind you, for those of us who programmed down to the bare metal on machines such as the PDP-11 the increment/decrement operators are (or appear to be) familiar, comfortable, and convenient. However it is open to question whether they belong in higher level languages. (They are entrenched in C but then …).
The usual argument for them is that they simplify and clarify incrementing/decrementing a variable, i.e., instead of saying
incrediblylongname = incrediblylongname + 1;we can say
incrediblylongname++;or even (with the same effect)
Now if this were the only use it would be a minor convenience in practice, a special case of the
add x to yform. However in C it is not the only use. Take for example the common idiom for copying an array:
while(*dst++ = *src++);Here we begin to see why the ++ and — operators create problems. The essence of the matter is that each application of these operators is an assignment and that these assignments can be in conflict, producing ‘undefined’ behaviour or, less severely, unexpected behaviour. In this case we can get little surprises if dst and src overlap. This plethora of assignments in C can be indefinitely expanded because assignments are expressions rather than statements. The end result is that there is a considerable amount of legalese in the C language definition that is there for handling the resulting special cases and ambiguity.
Note that the idiom has side effects; in this case that dst and src point one location past the end of the respective arrays. If we had written
for (;*dst = *src;dst++,src++);The two pointers would now point to the end of the arrays.
The upshot is that the increment/decrement operators in C create obscure special cases. They may be a gift of convenience, but they are a poisoned gift. The C programmer must either carefully step around the complexities or else don the robe of language lawyer and plunge boldly into the thicket. The increment/decrement operators may be a design flaw in the C language, but it doesn’t matter – C is cast in stone.
This page was last updated February 1, 2008.