The Prefix and Postfix Forms of the Increment Operator - C Operator

C examples for Operator:Increment Decrement Operator

Description

The Prefix and Postfix Forms of the Increment Operator

Demo Code

#include <stdio.h> 
int main(void) { 
  int total = 0;//from ww w  . ja v a  2 s.  c  om
  int count = 5;
  total = 6 + count++;  
  
  printf("total: %d",total);
  printf("count: %d",count);
  return 0; 
}

Result

With the same initial value of 5 for count, total is assigned the value 11.

This is because the initial value of count is used to evaluate the expression on the right of the assignment (6 + 5).

The variable count is incremented by 1 after its value has been used in the expression.

The preceding statement is therefore equivalent to these two statements:

Demo Code

#include <stdio.h> 
int main(void) { 
  int total = 0;/*from www  .j a  v a 2  s  .  c  o  m*/
  int count = 5;

  total = 6 + count;
  ++count;
  
  printf("total: %d",total);
  printf("count: %d",count);
  return 0; 
}

Result

For example, suppose a is 10 and b is 5 in the following statement:

Demo Code

#include <stdio.h> 
int main(void) { 
  int a = 10;// w w w .ja  v a  2 s . c o  m
  int b = 5;

  int x = a++ + b;  

  printf("a: %d",a);
  printf("b: %d",b);
  printf("x: %d",x);

  return 0; 
}

Result

x will be assigned the value 15 (from 10 + 5) because a is incremented after the expression is evaluated.

The next time you use the variable a, however, it will have the value 11.

On the other hand, suppose you execute the following statement, with the same initial values for a and b:

Demo Code

#include <stdio.h> 
int main(void) { 
  int a = 10;//from www. j av a2 s  .co m
  int b = 5;

  int y = a + (++b);

  printf("a: %d",a);
  printf("b: %d",b);
  printf("y: %d",y);

  return 0; 
}

Result

y will be assigned the value 16 (from 10 + 6) because b is incremented before the statement is evaluated.

It's a good idea to use parentheses to make sure there's no confusion.

Demo Code

#include <stdio.h> 
int main(void) { 
  int a = 10;/*from  ww  w.  j  a v  a 2  s .  c  o  m*/
  int b = 5;

  int x = (a++) + b;
  int y = a + (++b);

  printf("a: %d",a);
  printf("b: %d",b);
  printf("y: %d",y);

  return 0; 
}

Result


Related Tutorials