Are unspecified and undefined behavior required to be consistent between compiles of the same program with the same compiler in the same environment?

前端 未结 9 1150
清歌不尽
清歌不尽 2021-01-25 22:21

Let\'s pretend my program contains a specific construct the C++ Standard states to be unspecified behavior. This basically means the implementation has to do something reasonabl

9条回答
  •  情话喂你
    2021-01-25 23:02

    Undefined behavior can vary between runs of the same program, and even between execution of the same code in the same run of the program. As an example, the value of an uninitialized (automatic) variable is undefined, and then its actual value is just whatever value that happened to be at that place in memory. Obviously, this can vary.

    EDIT:

    This goes for unspecified behavior too. For example, the order of evaluation of function arguments is unspecified, so if they have side effects, those side effects can occur in any order. This may print "Hi!Ho!" or "Ho!Hi!":

    f( printf("Hi!"), printf("Ho!") );
    

    This can vary between executions, too. As the standard says: "An instance of the abstract machine can thus have more than one possible execution sequence for a given program and a given input." The difference is that with undefined behavior, anything can happen: the computer can explode, reformat the disk, or whatever. If the behavior is unspecified, the computer is not allowed to explode.

    There is also implementation-defined behavior, such as the value of sizeof(int). This must be the same at all times, for the same compiler.

提交回复
热议问题