+ 6

Quiz query, $d.$d--=20?

$d = 5; echo $d*$d--; The answer I believed was 25 but apparently it is 20. To try debugging, I did: echo $d.$d--; And I get 45. 5*4 alone is confusing for post decrement. Why is it 4*5? Can someone explain? Thanks!

5th Apr 2019, 10:25 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
10 Antworten
+ 3
Ipang you did it right, it took me a while too, to figure that out in C
6th Apr 2019, 6:15 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 3
Ipang maybe test em all the time before use, in a different language, with time you won't need that again
6th Apr 2019, 6:25 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 2
This is really odd, we commonly understood postfix operator doesn't change the operand's value at least until the next statement line was executed. It's funny how PHP treats postfix & prefix operator the same. I'm looking forward to hearing something about this odd behaviour. $d = 5; echo '$d * $d++ = ' . $d * $d++ . '<br>'; // output: 30 $d = 5; echo '$d * ++$d = ' . $d * ++$d . '<br>'; // output: 36 ?>
5th Apr 2019, 11:02 AM
Ipang
+ 2
Ipang I think it's working from right to left just like in C when you put such in a printf function ⚡Prometheus ⚡ this is probably the case
5th Apr 2019, 10:51 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 1
So I did a little test on different languages, and found that this operator associativity is shared amongst C, C++ and PHP. Java, C# and JavaScript seems to have different way in determining associativity and thus different output. I guess we just need to be more careful with this difference.
5th Apr 2019, 2:43 PM
Ipang
+ 1
*AsterisK* Out of curiosity I tested printing the results of the following expressions in several languages (in Code Playground) and I got different results: * Note before every evaluation <d> = 5 1. (d * d++) C, C++, PHP => 30 Java, C#, JS => 25 2. (d * ++d) C, C++, PHP => 36 Java, C#, JS => 30 3. (d * d--) C, C++, PHP => 20 Java, C#, JS => 25 4. (d * --d) C, C++, PHP => 16 Java, C#, JS => 20 I seem to get the impression that C, C++ and PHP does associativity evaluation differently with Java, C# and JavaScript. Or maybe I wasn't doing it right that the output differs.
6th Apr 2019, 6:05 AM
Ipang
+ 1
*AsterisK* I'm having difficulty when it comes to evaluating expressions, especially now that I'm aware of this various operator associativity evaluation from different languages, wish there was a way to easily remember which language does it how 😁
6th Apr 2019, 6:23 AM
Ipang
+ 1
*AsterisK* Good idea, I'll keep a note on this for future. Thanks mate 👍
6th Apr 2019, 6:44 AM
Ipang