C standard expression | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

31st Dec 2018, 1:10 PM
Aaditya Deshpande
Aaditya Deshpande - avatar
7 Answers
+ 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.
31st Dec 2018, 1:34 PM
Schindlabua
Schindlabua - avatar
+ 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.
2nd Jan 2019, 2:05 AM
Sonic
Sonic - avatar
+ 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
2nd Jan 2019, 7:40 AM
Schindlabua
Schindlabua - avatar
31st Dec 2018, 2:43 PM
Babak
Babak - avatar
+ 4
Another case for dr. UB - C++ Soldier (Babak)! 😉
31st Dec 2018, 1:14 PM
HonFu
HonFu - avatar
+ 3
Yeh Schindlabua that's right
2nd Jan 2019, 7:41 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 2
Thanks for that resource C++ Soldier (Babak)
2nd Jan 2019, 12:15 AM
✳AsterisK✳
✳AsterisK✳ - avatar