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 that is for example

x--;

denote postfix-decrement operator and

--x;

denote prefix decrement operator.


Having seen the difference with respect to notation now let us see the difference between both prefix and postfix with respect to functionality. 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 other words in postfix increment or decrement operation the 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 eth operators gets executes is decided by precedence of operators. Associativity is the order n 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. That is the operator gets executed from right to left in an expression.

Now let us see how postfix and prefix increment and decrement operator gets evaluated as


Program1:


main()

{

int a=5,b;

b= ++a + 5;

printf("a=%d b=%d",a,b);

}


Program2:

main()

{

int a=5,b;

b= a++ + 5;

printf("a=%d b=%d",a,b);

}


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

a=6 b=11


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

a=6 b=10


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 operate in the same speed and have no difference in this regard.

Questions by GeekAdmin   answers by GeekAdmin

 

This Question is not yet answered!

 
 

Related Answered Questions

 

Related Open Questions