+ 8
C standard expression
How come that the C standard says that the expreassion j=i++ * i++; is undefined, where as the expression j=i++ && i++; is perfectly legal
7 Antworten
+ 9
HonFu first :P
`&&` is a "sequence point", and `*` is not.
You can't have more than one side effect within a single sequence (at least you need to be careful), and `i++ * i++` has two.
Since there is no sequence point between `i++` and `i++`, we can't say when exactly which will happen (before multiplying? after?)
So it is undefined behaviour.
The sequence point in `i++ && i++` makes sure that the side effect of the left `i++` happens before we move to the right side. So it's not undefined.
I believe `&&` is a sequence point to allow "short-circuiting". For example, `false && x` will just be `false`, and you don't even have to look at what `x` is.
To fully get it you'll have to read up on sequence point rules I think.
+ 9
Schindlabua does this concept of sequence points also apply to other programming languages like Php? I guess it does. I have seen at least one Php Sololearn challenge question which asks about the result of a "multiplication with increment" operation (which I can't locate right now but is something like the result of $i++ * $i++) for which I now think that the answer would be undefined.
+ 7
Sonic No that's strictly C only! C++ has something similar (sequenced relations).
Most other languages I know do the operations left-to-right and so everything is defined always.
C does it like that so it can optimize code better. And it never really matters in practice because nobody writes statements like `i++ * i++` :P
+ 6
+ 4
Another case for dr. UB - C++ Soldier (Babak)! 😉
+ 3
Yeh Schindlabua that's right
+ 2
Thanks for that resource C++ Soldier (Babak)