+ 1

x-- and --x

can someone explain what is the difference between x-- and --x?

26th Oct 2016, 5:41 AM
Ricky Effendi
Ricky Effendi - avatar
3 ответов
+ 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.
26th Oct 2016, 5:57 AM
DaemonErrors
DaemonErrors - avatar
+ 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!!!
26th Oct 2016, 8:27 AM
Taha Ansari
Taha Ansari - avatar
+ 1
hmm.. im still confused but i think i get the point. thanks for explaining dude.
26th Oct 2016, 6:01 AM
Ricky Effendi
Ricky Effendi - avatar