Different from the first thoughts, this program does actually not show undefined behaviour, as each expression doe not violate (C11, 6.5/2). In brief: each expression only has one side-effect and each expression per se is clearly defined (each would very well work as expression statements or the right side of an assignment).
Suspect are actually just these lines:
printf("%c %c\n",ch,++ch);
printf("%d %d %d\n",a=a+2,-a + ++b%a,a<<2);//
After each sequence point (roughly: function call), all variables are well-defined.
However, the actual values passed to printf vary, as the sequence the expressions for the arguments are evaluated is not defined (5.1.2.3/2 - indeterminately sequenced). So, for the first line, either ch
or ch+1
is passed as the first argument, depending which argument expression is evaluated first. The second argument is, however always ch+1
.
Comments welcome, please cite the standard, no second/3rd source. Yes, that is a gauntlet thrown down.
Disclaimer: this code is of course crap. This I will not discuss. It is, however, a good exercise for students exactly to enforce the question as asked. (wereas I wonder if there is no other like this already - the ones given in the comments are actually not, as they do exhibit UB). It is vital actually to sensitize programmers for this problem, which is very specific to C-like languages as those do allow side-effects for expressions.
Edit:
After further thinking, I am not that sure anymore. As my chain of prove is missing a link which I cannot find (lack of understanding the english phrases or just being too stupid), I will accept to treat this as UB now. While still in doubt, the behavior is bad however it would be called and has no application beyond as an example for - at least - ambivalent coding. I leave it here in hope, someone might stumble around and show up the final solution.
Thanks @AlbertoM for watering the seed of doubt.