Do the above two programs have the same observable behavior?
As you say, it depends on whether srand() and rand() have observed side effects. They should not; there can be no external noise source, since the sequence must be repeated for a given seed, and there is no other reason for doing I / O or accessing volatile data.
If the compiler can determine that they do not (for example, if they are defined inside the line in the header or the linker is smart enough to perform additional optimizations), then he can omit them; otherwise, he must assume that they are doing this and turn them on. In many implementations, these functions will be in a precompiled library, and the linker will not be so smart, so you will end up calling the functions; however, a decent compiler should notice that both if branches are identical and omit the test.
(UPDATE: as noted in the comments, the call to rand() can also be omitted only if the compiler can determine that no future observable behavior can depend on its side effects).
How do I know if two given programs have the same observable behavior?
In general, this is a very complex problem, and there will be some programs where it is impossible to say (for reasons similar to the stop problem). For such simple programs, you can simply list the observed operations and compare them; if the behavior depends on the input of the program in a non-trivial order, then it will very soon become very difficult.
Mike seymour
source share