Can code that will never be executed invoke undefined behavior?

后端 未结 9 1645
予麋鹿
予麋鹿 2020-11-27 17:52

The code that invokes undefined behavior (in this example, division by zero) will never get executed, is the program still undefined behavior?

int main(void)         


        
9条回答
  •  伪装坚强ぢ
    2020-11-27 18:34

    On the subject of undefined behaviour it is often hard to separate the formal aspects from the practical ones. This is the definition of undefined behaviour in the 1989 standard (I don't have a more recent version at hand, but I don't expect this to have changed substantially):

    1 undefined behavior
      behavior, upon use of a nonportable or erroneous program construct or of
      erroneous data, for which this International Standard imposes no requirements
    2 NOTE Possible undefined behavior ranges from ignoring the situation completely
      with unpredictable results, to behaving during translation or program execution
      in a documented manner characteristic of the environment (with or without the
      issuance of a diagnostic message), to terminating a translation or
      execution (with the issuance of a diagnostic message).
    

    From a formal point of view I'd say your program does invoke undefined behaviour, which means that the standard places no requirement whatsoever on what it will do when run, just because it contains division by zero.

    On the other hand, from a practical point of view I'd be surprised to find a compiler that didn't behave as you intuitively expect.

提交回复
热议问题