The evaluation result in java and js is 5, but in PHP it is 4
Is it because my formula is not written in a standard way? Or is it for other reasons? I asked others to try it using .net and c language, and all the results were 5
[Solved] Thank you for your answers. My guess is that the formula is not very standardized, because I always feel that The ternary is from right to left, so I omitted the last bracket (I often wrote it this way before). I will correct it. For the sake of standardization, it should be 3<8?(9<6?7:5):(2>0 ?4:1)
typecho2017-06-08 11:04:07
The problem with the combination direction of the ternary operator:
java from right to left. Equivalent to 3<8?(9<6?7:5):(2>0?4:1)
php from do to right. Equivalent to (3<8?(9<6?7:5):2)>0?4:1
Therefore, in order to avoid the generation of ambiguous code, it is better not to omit the parentheses that should be written
过去多啦不再A梦2017-06-08 11:04:07
PHP’s ternary operation combination order is reverse
http://www.jianshu.com/p/124f...
代言2017-06-08 11:04:07
I guess PHP interprets priorities differently from Java, JS and other languages. It may be interpreted as (3 < 8 ? (9 < 6 ? 7 : 5) : 2 > 0) ? 4 : 1
某草草2017-06-08 11:04:07
In PHP it looks like this:
$a = (3 < 8 ? (9 < 6 ? 7 : 5): 2 > 0)
? 4
: 1;
So it’s 4;
In JavaScript it looks like this:
var a = (3 < 8)
? (9 < 6 ? 7 : 5)
: (2 > 0 ? 4 : 1);
So it’s 5.
So if you don’t know the precedence of the operator, just complete the brackets. ^_^