Latest web development tutorials

C ++ increment decrement operators

C ++ operator C ++ operator

Increment operator ++ will operand by 1, decrement operator - will operand minus 1. therefore:

x = x+1;
 
等同于
 
x++;

same:

x = x-1;
 
等同于
 
x--;

Whether increment or decrement operator operator can be placed before the operand (prefix) or after (suffix). E.g:

x = x+1;
 
可以写成:
 
++x; // 前缀形式

or:

x++; // 后缀形式

There is little difference between the prefix and suffix forms form. If you use the prefix form, then complete the increment or decrement expression is evaluated before, if you are using postfix form, the expression will be calculated after the completion of increment or decrement.

Examples

Consider the following examples, understand the difference between the two:

#include <iostream>
using namespace std;
 
main()
{
   int a = 21;
   int c ;
 
   // a 的值在赋值之前不会自增
   c = a++;   
   cout << "Line 1 - Value of a++ is :" << c << endl ;
 
   // 表达式计算之后,a 的值增加 1
   cout << "Line 2 - Value of a is :" << a << endl ;
 
   // a 的值在赋值之前自增
   c = ++a;  
   cout << "Line 3 - Value of ++a is  :" << c << endl ;
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Line 1 - Value of a++ is :21
Line 2 - Value of a is :22
Line 3 - Value of ++a is  :23

C ++ operator C ++ operator