Tuesday 12 February 2013

Increment and Decrement Operators in C Programming



Incrementing or decrementing by 1 is such a common computation that C offers several shorthand versions of the above type of assignment. For instance:

total = sum++;

and

total =++sum;

The first statement is equivalent to:

total = sum;
sum = sum+1;

while the second is the same as:

sum = sum + 1;
total = sum;

Obviously, the above statements A and B do not have the same effect. The ++ in sum++ is called the postincrement operator while that in ++sum is called the preincrement operator, and appropriately so.

In the following for construct:

for(ctr=0;ctr++<10;..)
the value of ctr is compared to 10 and then increment after which the loop is entered.
On the other hand, if the construct is modified to:

for (ctr=0;++ctr <10;..)

the value of ctr is first incremented, and then compared to 10, and then the loop is entered. Thus in the first case the body of the loop will be executed 10 times, whereas in the latter case it will be executed 9 times only.

0 comments:

Post a Comment

Powered by Blogger.