Common interview question that confuses many Programmer is "what is difernce b/w pre and post increment operator( i++ and ++i )", And 70% programmers failed to speak correct answer.
The increment operator increases its operand by one.The decrement operator decreases its operand by one.for example this statement x=x+1 can be rewritten like this by use of increment operator x++,
similarly the statement x=x-1 is equivalent to x--.
In the forgoing example thre is no diference in prefix and postfix forms.
e.g
In this tutorial i will teach you all concept about increment/decrement operator.
The increment operator increases its operand by one.The decrement operator decreases its operand by one.for example this statement x=x+1 can be rewritten like this by use of increment operator x++,
similarly the statement x=x-1 is equivalent to x--.
Is thre any diference in Pre-increment ++i and Post-increment i++ ??
e.g
x=5;
x++
or
x=5
++x;
However when the increment and decrement operator are part of a large expression then a subtle,yet powerful diference b/w these two forms apears.
In the Prefix form ,the operand is incremented or decremented before the value is obtained for use in the expression.
In Postfix form the previous value is obtatined for use in the expression ,and then the operand is modified.
For Example:
x=65;
y=++x;
in this case y is set to 66 as you would expect,because the increment occurs before x is asigned to y. thus the line ++x ; is equivalent of these two statements;
x=x+1;
y=x;
Howewer,when written like this:
x=65;
y=x++;
the value x is obtained before the increment operator is executed ,so the value of y is 65. Of course in both cases x is set to 66 .Here the line y=x++; is equivalent to these two statements:
y=x;
x=x+1;
No comments:
Post a Comment