c++gccvisual-c++

Strange behavior with C++ compilers optimizing infinite loops?


The following code is intended to have an infinite loop without termination and without output. Compiling with MSVC 2022 and GCC 14 and -O2 flag I obtained the same wrong behavior (output is produced).

// main.cpp
#include <test.h>

int main()
{
    Test t;
    t.test();
    return 0;
}

// test.h
#pragma once

class Test
{
public:
    void test();

private:
    int m_i = 0;
};

// test.cpp
#include "test.h"

#include <iostream>

void Test::test()
{
    while (true) {
        if (m_i > 100) {
            std::cout << "m_i is " << m_i << std::endl;
            return;
        }
    }
}

the output is the following

m_i is 0

substituting the test function with the following

void Test::test()
{
    while (true) {
        if (int i = m_i; i == 100) {
            std::cout << "m_i is " << m_i << std::endl;
            std::cout << "i is " << i << std::endl;
            return;
        }
    }
}

the output on GCC is the following

m_i is 0
i is 100

Debugging the code they seems both optimization bugs. Are there any useful references and rules to keep in consideration to avoid similar problems in advance? I encountered this problem debugging a memory corruption substituting and removing code, and I have been mislead for a while.


Solution

  • The C++ standard says a C++ implementation may assume a program does not have any infinite loops that do not either terminate or do “something useful.” Quoting from C++ draft N4849 6.9.2.2 [intro.progress]:

    The implementation may assume that any thread will eventually do one of the following:

    (1.1) — terminate,

    (1.2) — make a call to a library I/O function,

    (1.3) — perform an access through a volatile glvalue, or

    (1.4) — perform a synchronization operation or an atomic operation.

    [Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. —end note]

    So this is not an optimization bug; it is allowed behavior. Essentially, C++ programmers are expected to know about this rule and not write code with an infinite loop that does nothing. The rule allows compilers to apply optimizations to loops that do terminate or do something useful but that the compiler may be unable to analyze fully.