I saw this meme on Instagram about some C++ code that should not output anything but does. The code is:
#include <iostream>
int main() {
while (1)
;
}
void unreachable() {
std::cout << "Hello World!" << std::endl;
}
I compiled it with clang as shown in the meme and got the same result (Ubuntu clang version 14.0.0-1ubuntu1.1
) but the same code compiled with gcc does what you expect: nothing (g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
).
I would like to know why clang does things different and how the hack the unreachable function is executed if I never call it from the main function.
>Solution :
In
#include <iostream>
int main() {
while (1)
;
}
void unreachable() {
std::cout << "Hello World!" << std::endl;
}
The never-ending do-nothing loop breaks the rules. As per [intro.progress]
The implementation may assume that any thread will eventually do one of the following:
- terminate,
- make a call to a library I/O function,
- perform an access through a volatile glvalue, or
- perform a synchronization operation or an atomic operation.
[Note 1: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. — end note]
Since the program is invalid, the compiler is allowed to do anything it wants from generate a program that does what you expect, GCC’s response, to literally anything else. So technically clang’s result is valid. Be grateful. The compiler could have opted to produce Skynet.