Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clang++ compiles unreachable function, g++ doesn't

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;
}

c++ meme

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading