How does the prefix and postfix operator on expression?
The operators present in prefix and postfix are
- prefix increment operator denoted by ++
- prefix decrement operator denoted by —
- postfix increment operator
- postfix decrement operator
The difference between the two is that in the postfix notation, the operator appears after postfix-expression, whereas in the prefix notation, the operator appears before expression, for example
denote postfix-decrement operator and
denote prefix decrement operator.
The prefix increment operator adds one to its operand. This incremented value is used in the expression to get the result of the expression. The prefix decrement operator is similar to the prefix increment operator, except that the operand is decremented by one and the decremented result is used in the expression to get the value of the expression.
In the postfix form, the increment or decrement takes place after the value is used in expression evaluation.
In prefix increment or decrement operation the increment or decrement takes place before the value is used in expression evaluation.
Also precedence denotes the priority of operators. In other words if number of operators occur in a expression the priority in which the operators gets executes is decided by precedence of operators.
Associativity is the order in which a operator gets executes. Prefix and postfix gets the highest precedence among the operators and the associativity of these is from right to left. The operator gets executed from right to left in an expression.
How postfix and prefix increment and decrement operator gets evaluated
b= ++a + 5;
b= a++ + 5;
In this program1 makes use of prefix increment operator that is ++a so value of a is incremented and then used in expression which gives
a=a+1 which gives value of a as 6
then b becomes b=6+5=11
so the output of prgram1 is
In this program2 makes use of postfix increment operator that is a++ so value of a is used in expression with then incremented which gives
b = 5+5=10
a=a+1 makes value of a as 6
so the output of prgram2 is
The prefix and postfix have difference only in the way they operate and have nothing to do in terms of execution speed. In other words both prefix and postfix operate in the same speed and have no difference in this regard.