As postfix has greater precedence than prefix, the...
# getting-started
h
As postfix has greater precedence than prefix, then why
Copy code
var num = 0
println(--num + num++) // equals to -2 instead of 0
a
I do not have the answer, but if I see such code during the code review, I ask to change it. I would vote to complete remove all the legacy of C.
👍 2
e
I supose it's because the plus operator evaluates both operands before adding them: (--num) {decrements 'num' to -1, returns -1}, (num++) {returns -1, increments 'num' to 0 }, plus operator { adds -1 and -1, returns -2}
☝️ 2
r
@El Anthony is correct. The relative precedence of the postfix and prefix operators would only come into play for something like
--num++
. Your code has nothing to do with precedence and everything to do with the fact that the
+
operator evaluates its arguments left to right.
h
Yeah cracked it already after a little brainstorming
k
Andrey:
I do not have the answer, but if I see such code during the code review, I ask to change it. I would vote to complete remove all the legacy of C.
"All the legacy of C" includes curly brackets and the syntax of while loops. Which parts of C legacy would you remove? The expression
--num + num++
is (and has always been) already specified to result in undefined behaviour in C and therefore most IDEs will warn you about it. Java and Kotlin had decided to change that to be fully specified so they have in fact added further support to that syntax instead of removing it.
a
++ and -- (both in pre and post variant) bring nothing but confusion. If they completely vanish, we will only gain readability (and encourage immutability) (I am sorry I need more time to think about other C legacy.)
k
There's also
num += 1
. In C and Java,
++num
means exactly the same thing as `num += 1`: it increments
num
and the result of the expression is its new value. However, Kotlin made
num += 1
a statement but kept
++num
as an expression. Why?
a
Thank you ! This is also a legacy to be removed. Mutable, ugly, unreadable.
m
sometimes mutability is wanted/needed. I prefer a world where vars CAN still be mutable. num++ and num-- being remnants is okay, but its usage should be discouraged, not removed.
a
if you still have this you loose nothing:
num = num + 1
readable, explicit.
k
array[expensiveFunction()] = array[expensiveFunction()] + 1
???
a
Sure !!! Exactly to prevent anyone to write something like this:
--array[--expensiveFunction()]++
The code is written for humans:
index = expensiveFunction()
array[index] = array[index] + 1
k
That says to me: is
index
used anywhere else? Better check the rest of the function. I would be happy with losing ++ and -- operators, but would find
array[complex_expression] += 1
clearer to read.