469,572 Members | 1,287 Online

19
hi everyone well i m little bit confused about the use of pre an post increment infact my thinking contradict with the logic of programe
lets consider an example
x=5;
y=x++;
z=x;
after the execution of these statments value of y will b 5 while value of z will be 6
WHY?
value of x++ and x=x+1is equal it first assign a value of x to y then increment in x. why?
expression on the right must be executed first then it must assign value to y
mean to saty value of y must be 6 just like pre increment.
if not then what about the given expression
y=x*3+2;
in this case why it is not assigning a value of x to y first and then solving expression?
although it first solve expression and then assign its value to y.
Nov 28 '06 #1
1 2077
horace1
1,510 Expert 1GB
the ++ and -- operators are prefix or postfix
(1) postfix (e.g. i++ or i--) the value of the operand is used in the expression then it is incremented or decremented.
(2) prefix (e.g. ++i or --i) the value of the operand is incremented or decremented and the new value used in the expression.

For example, assuming i = 10
Expand|Select|Wrap|Line Numbers
1.    k = i++; after assignment k would = 10 and i = 11
2.    k = ++i; after assignment k would = 11 and i = 11
3.
Now, assuming i = 10 and j = 2 consider the expressions (which may be part of a larger expression):
Expand|Select|Wrap|Line Numbers
1.    i * j++  result = 20, j = 3 (incremented after evaluation)
2.    i * ++j  result = 30, j = 3 (incremented before evaluation)
3.    i * j--  result = 20, j = 1 (decremented after evaluation)
4.    i * --j  result = 10, j = 1 (decremented before evaluation)
5.
does that help?

by the way don't do
Expand|Select|Wrap|Line Numbers
1. i=i++;
2.
you don't know if the ++ is done before or after the assignment - it is undefined
Nov 28 '06 #2