0

I am aware of the phenomenon of undefined behavior due to order of evaluation in C++. As an example, I was exposed to the following snippet of code from the C++ Primer:

cout << i << " " << ++i << endl; //undefined

as well as:

int i = f1() * f2(); //f1 or f2 could both be evaluated first.

I've tried implementing both of these to play around with the phenomenon and see it in action. However, peculiarly enough, after executing the program, I always get the same result, even though my expectation is that it would randomly flip flop between the two possible results. For the first, for example, I should be seeing 1 1 and 0 1 but instead, I always see 1 1.

I originally thought that maybe it is based on something like the current state of the machine, kind of like how the random number generators and their seeds work in Java but I have no way to prove this.

Why is this?

May
  • 77
  • 1
  • 10
  • Undefined behaviour can be literally anything, including the appearance of behaving correctly/consistently/predictably. – Paul R Jul 04 '15 at 08:04
  • Undefined behavior is only undefined insofar as the C++ standard is concerned. Particular implementations may very well have perfectly predictable behavior for certain classes of UB. And for the examples you show, I can't see any reason why, for most implementations, it wouldn't be 100% predictable (as long as you have a thorough understanding of the internal workings of your particular implementation). – Benjamin Lindley Jul 04 '15 at 08:12
  • Ah, I see. I was always thinking that the behavior must be unpredictable! Thanks for the clarification. – May Jul 04 '15 at 08:21

0 Answers0