C Language / Lesson 4 Back to Index or to Previous Page or to Next Page

Increment and Decrement Operators

The increment and decrement operators ++ and -- respectively increase or decrease an lvalue by 1.
In the special case of pointers the pointer is increased or decreased by the size of the pointed element.

Prefix - Postfix

++v  First increase v then use the value of v

v++  First use the value of v then increase v

All examples following use the ++ operator. Similar are the usages of the -- operator.
  Case I: Assignments a=++b ; vs. a=b++;
  Case II: Indices a[++i] vs. a[i++]
  Case III : Conditions if (... ++x ...) vs. if (... x++...)
  Case IV : Passing parameters func(++a) vs. func(a++)
  Case V : Pointers  
Expression First Then
*p++ use value increase pointer
*++p increase pointer use value
++*p increase value use value
(*p)++ use value increase value

 

Sample function using indirection and increment operators

short
strlen(char *s)
{   short i;
    i=0;
    while (*s++)
        ++i;
    return i;
}

Example

char *   // Fill a string with asterisks
fill_stars(char *s)
{    
  do 
  *s++='*' ; // First assign the asterisk then increase the pointer
  while (*s!='\0')
}    
     

Back to top or to Previous Page or to Next Page