+ 1
x-- and --x
can someone explain what is the difference between x-- and --x?
3 Antworten
+ 6
There's actually a huge difference between the two. x-- is called the postfix-operator, and --x is called the prefix-operator. With the prefix operator, (--x), in this case, the value of x is decremented, and the value of the expression is the new value of x. e.g
int x = 1;
--x; // the value of x is now 0
Now with the postfix operator. The variable 'x' (x--) is evaluated before it is decremented.
Here's an example:
int foo(int x = 10) {
return x--;
}
The function "foo" will return the value of 10, because the variable 'x' is decremented AFTER it was evaluated, whereas if you did this:
int foo(int x = 10) {
return --x;
}
The function would return a value of 9, because it was decremented before it was evaluated.
This works the same way for ++ as well. Hope this helped.
+ 3
it's simple,
--x will be decremented first and then gets evaluated.
whereas the x-- will be evaluated first and then gets decremented.
for example,
int a =5, b =5;
int c= --a;
// here, c =4 and a=4 after evaluation.
//why? Because variable a got decremented first
// and then the expression evaluated.
//similarly,
int d= b--;
//here, d=5 and b=4 after evaluation.
//why?
//Because the expression "d=b--" first get evaluated
//and then the variable b is decremented.
Hope you understood!!!
+ 1
hmm.. im still confused but i think i get the point. thanks for explaining dude.