Increment and Decrement Operators

Adding or subtracting 1 from a variable is a very common programming practice.  Adding 1 to a variable is called incrementing and subtracting 1 from a variable is called decrementing.

  • increment and decrement operators work only with integer variables -- not on floating point variables or literals.

  • the C++ compiler is controlling the execution of the prefix and postfix operators.  You cannot change this order of execution.  For example, the parentheses below will not force an early execution: 
    value = (((x--)))* num;   //still decrements x last.

  • one disadvantage of using the increment/decrement operators is that the variable can only be incremented or decremented by the value ONE.  If you need to increment (or decrement) by a larger (or smaller) value, you must use statements like
     m += 2;  or  amount -= 5;

  • be careful when combining increment and decrement operators inside expressions with logical operators.  If in doubt, don't use them together.  For example, do NOT use:
    if (( num1 = = 4 ) || ( num2 != ++j)) 
    (j may not be incremented when (num1 = = 4) is TRUE.)
    Instead, separate the code to avoid this problem:
    ++j;
    if (( num1 = = 4) || (num2 != j))

 

 

All are the same:
i = i + 1;
 i += 1;
i++;


Prefix:
++i;
--i;
increment or decrement occurs
before the variable's value is used in the remainder of the expression.

Postfix:
i++;
i--;
increment or decrement occurs
after the variable's value is used in the remainder of the expression.


 

Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use