Infolinks In Text Ads

Friday, 22 July 2011

Chapter 7: More Operators


Chapter 7: More Operators

In this chapter we'll meet some (though still not all) of C's more advanced arithmetic operators. The ones we'll meet here have to do with making common patterns of operations easier.

It's extremely common in programming to have to increment a variable by 1, that is, to add 1 to it. (For example, if you're processing each element of an array, you'll typically write a loop with an index or pointer variable stepping through the elements of the array, and you'll increment the variable each time through the loop.) The classic way to increment a variable is with an assignment like

i = i + 1
Such an assignment is perfectly common and acceptable, but it has a few slight problems:
As we've mentioned, it looks a little odd, especially from an algebraic perspective.
If the object being incremented is not a simple variable, the idiom can become cumbersome to type, and correspondingly more error-prone. For example, the expression
a[i+j+2*k] = a[i+j+2*k] + 1
is a bit of a mess, and you may have to look closely to see that the similar-looking expression
a[i+j+2*k] = a[i+j+2+k] + 1
probably has a mistake in it.
Since incrementing things is so common, it might be nice to have an easier way of doing it.
In fact, C provides not one but two other, simpler ways of incrementing variables and performing other similar operations.

7.1 Assignment Operators

7.2 Increment and Decrement Operators

7.3 Order of Evaluation

Twitter Delicious Facebook Digg Stumbleupon Favorites More