4 ms·
I am not familiar with undefined behaviour. Why exactly can't such behaviour be caught during compile-time?
by prudhvis 12y ago
I am not familiar with undefined behaviour. Why exactly can't such behaviour be caught during compile-time?
- pcwalton 12y agoThere are at least three ways I can see to answer your question, all of them answering it in different ways: 1. It's undecidable, because precisely detecting undefined behavior according to the C and C++ standards in general reduces to the halting problem. It's perfectly defined to have a program that dereferences a null pointer in a branch that is never actually taken at runtime. 2. The type systems of C and C++ were not designed to be restrictive/expressive enough to disallow undefined behavior, for a multitude of reasons (simplicity of implementation [especially in 1973], backwards compatibility, concerns over performance). 3. Defining away all undefined behavior via the runtime system (e.g. NaCl or asm.js) requires a sophisticated runtime and incurs a performance penalty. The first explains why C and C++ compilers cannot catch all undefined behavior. The second explains why the C and C++ languages do not disallow undefined behavior. The third explains why most C/C++-based systems do not disallow undefined behavior at runtime.
- mikeash 12y agoFor an easy example, consider the following function: int next(int x) { return x + 1; } This invokes undefined behavior in the case where x = INT_MAX. Yet if this produced a compile-time diagnostic, it would be tremendously irritating and generally useless. Worse than useless, as it would swamp real diagnostics.