Consider this body of main:
std::srand(std::time(nullptr));
while (std::rand());
Surprisingly, I couldn’t find anything, whether it be in the spec, on Google, or on this website, about whether that is well-defined. As for the spec:
N3485 § 6.5/4 [stmt.iter] says this about the condition:
[ Note: The requirements on conditions in iteration statements are described in 6.4. — end note ]
However, looking through 6.4, I saw nothing that refers to this scenario. In theory, the loop could virtually go on forever, but in practice, I usually had a run time of 5ms, with one time in all test runs being 22ms.
Is it well-defined behaviour to base the loop termination condition on a changing (pseudo)random number? If it isn’t, which kind of behaviour is it?
std::rand()will be called at each iteration, then the loop will go on or not depending on its return value.There is no reason to have any undefined behavior here.
It’s not different from doing something like this
Why do you think this case would be special?