Increment and Decrement Operator- Definition
Increment and Decrement Operator
C/C++ includes two useful operators not generally found in other computer
languages. These are the increment and decrement operators, ++ and — . The operator ++ adds 1 to its operand, and — subtracts one. In other words:
x = x+1;
is the same as
++x;
and
x = x-1;
is the same as
x–;
Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand. For example,
x = x+1;
can be written
++x;
or
x++;
There is, however, a difference between the prefix and postfix forms when you use these operators in an expression. When an increment or decrement operator precedes its operand, the increment or decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, Operator Action
- Subtraction, also unary minus
+ Addition
* Multiplication
/ Division
% Modulus
– – Decrement
++ Increment
Arithmetic Operators
the value of the operand is obtained before incrementing or decrementing it. For
instance,
x = 10;
y = ++x;
sets y to 11. However, if you write the code as
x = 10;
y = x++;
y is set to 10. Either way, x is set to 11; the difference is in when it happens.
Most C/C++ compilers produce very fast, efficient object code for increment and decrement operations—code that is better than that generated by using the equivalent assignment statement. For this reason, you should use the increment and decrement operators when you can. Here is the precedence of the arithmetic operators:
| highest | ++ – – | – (unary minus) | */% |
| lowest | +– |
Operators on the same level of precedence are evaluated by the compiler from left to right. Of course, you can use parentheses to alter the order of evaluation. C/C++ treats parentheses in the same way as virtually all other computer languages. Parentheses force an operation, or set of operations, to have a higher level of precedence.
Popularity: 1% [?]
Posted on December 13, 2009 at 7:32 am
why and whan we use Increment and Decrement Operator ??