This C++ code, perhaps surprisingly, prints out 1
.
#include <iostream>
std::string x();
int main() {
std::cout << "x: " << x << std::endl;
return 0;
}
x
is a function prototype, which seems to be viewed as a function pointer, and C++ Standard section 4.12 Boolean conversions says:
4.12 Boolean conversions [conv.bool] 1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
However, x
is never bound to a function. As I would expect, the C linker doesn't allow this. However in C++ this isn't a problem at all. Can anyone explain this behavior?
int f() { return 1 / 0; }
is OK as long asf()
is never called). – Anaptyxismain
does call it,main
(that is, the program) doesn't contain UB. – Clemenceau