Does an expression with undefined behaviour that is never actually executed make a program erroneous?

前端 未结 9 951
情歌与酒
情歌与酒 2020-12-31 02:05

In many discussions about undefined behavior (UB), the point of view has been put forward that in the mere presence in a program of any construct that has UB in a p

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 02:50

    Deciding whether a program will perform an integer division by 0 (which is UB) is in general equivalent the halting problem. There is no way a compiler can determine that, in general. And so the mere presence of possible UB can not logically affect the rest of the program: a requirement to that effect in the standard, would require each compiler vendor to provide a halting problem solver in the compiler.

    Even simpler, the following program has UB only if the user inputs 0:

    #include 
    using namespace std;
    
    auto main() -> int
    {
        int x;
        if( cin >> x ) cout << 100/x << endl;
    }
    

    It would be absurd to maintain that this program in itself has UB.

    Once the undefined behavior occurs, however, then anything can happen: the further execution of code in the program is then compromised (e.g. the stack might have been fouled up).

提交回复
热议问题