Tuesday, April 5, 2011

Increment and Decrement Operators In C

In addition to the usual `-', C also has two other interesting unary operators, `++' (increment) and `--' (decrement).  Suppose we want to count the lines in a file.
main( ) {
               int c,n;
               n = 0;
               while( (c=getchar( )) != '\0' )
                       if( c == '\n' )
                               ++n;
               printf("%d lines\n", n);
       }
++n is equivalent to n=n+1 but clearer, particularly when n is a complicated expression.  `++' and `--' can be applied only to int's and char's (and pointers which we haven't got to yet).The unusual feature of `++' and `--' is that they can be used either before or after a variable.  The value of ++k is the value of k after it has been incremented.  The value of k++ is k before it is incremented.  Suppose k is 5.  Then
x = ++k;
increments k to 6 and then sets x to the resulting value, i.e., to 6.  But
x = k++;
first sets x to to 5, and then increments k to 6.  The incrementing effect of ++k and k++ is the same, but their values are respectively 5 and 6.

0 comments:

Post a Comment

Breaking News
Loading...
Quick Message
Press Esc to close
Copyright © 2013 Crack o Hack & tweak STORE All Right Reserved