+ 13
Why PHP gives output like this in given example?
I am confused why PHP gives weird output. In below given code I have taken 4 examples and according to my knowledge 2nd and 4th are correct but I didn't get why different output in 1st and 3rd example. Does anyone know how post and pre increment works in PHP. https://code.sololearn.com/w07HrjxKNOct/?ref=app
3 ответов
+ 8
This is because of the fact that value of same variable is being changed twice between sequence points, once using "++" and other using assignment operator"="
This leads to an undefined behaviour.
It is not specific to php as you can see the same stuff happening in C/C++ also(but there compiler generates the warning regarding the undefined behaviour of operations)👇
https://code.sololearn.com/crwhsQree03w/?ref=app
+ 6
Yes, indeed this confused me too, but I get to understand it this way..., that specially when arithmetic operations are performed with pre- and post- increments, the following rule is followed..., for example
$a * $a++ == $a++ * $a,
just the same as
$a--* $a == $a* $a--
$a++ - $a == $a-$a++
etc.....
+ 1
This is *my observation* here,
Flow of execution:
(evaluation is right to left, replacing values left to right..)
But it includes, definitely undefined behavior in different compilers...
$a = 10
$a = $a - $a++;
$a = $a - 10, $a++ => $a + 1= 11
$a = 11 - 10
$a = 1
$b = 10
$b = $b++ - $b++;
$b = $b++ - $b; $b++
$b = 11 - $b; $b++
$b = 11 - 12 = -1
$c = 5
$d = $c * $c++;
=$c * 5, $c++;
=6 * 5 => $d = 30
$e = 5
$f = $e++ * $e;
= 5 * $e , $++
$f = 5 * 6
= 30