Hassaan
09/03/2022, 1:00 PMvar num = 0
println(--num + num++) // equals to -2 instead of 0
AndreyVanDenHaag
09/03/2022, 1:14 PMEl Anthony
09/03/2022, 1:37 PMRuckus
09/03/2022, 3:58 PM--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.Hassaan
09/03/2022, 4:06 PMKlitos Kyriacou
09/04/2022, 12:17 PMI 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.AndreyVanDenHaag
09/05/2022, 5:07 AMKlitos Kyriacou
09/05/2022, 8:05 AMnum += 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?AndreyVanDenHaag
09/05/2022, 8:21 AMMichael de Kaste
09/05/2022, 1:40 PMAndreyVanDenHaag
09/05/2022, 1:52 PMnum = num + 1
readable, explicit.Klitos Kyriacou
09/05/2022, 3:02 PMarray[expensiveFunction()] = array[expensiveFunction()] + 1
???AndreyVanDenHaag
09/05/2022, 3:10 PM--array[--expensiveFunction()]++
AndreyVanDenHaag
09/05/2022, 3:12 PMindex = expensiveFunction()
array[index] = array[index] + 1
Klitos Kyriacou
09/05/2022, 3:15 PMindex
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.