문제

So I was playing around with some thought experiments where I imagined what would happen when two functions became mutually recursive. One such one was what if both functions could potentially fall into an infinite loop.

To that end, I thought up of this simple example:

#include <iostream>
#include <cstdlib>

int foo(int x);
int bar(int x);


int foo(int x)
{
    return bar(x + 1);
}

int bar(int x)
{
    return foo(x - 1);
}

int main(int argc, char **argv)
{
    if (argc > 1)
        std::cout << "The value is: " << foo(atoi(argv[1])) << std::endl;

    return 0;
}

Interestingly, this will actually print out absolutely nothing if you compile it with g++. Compile it with any -O switch and it falls into an infinite loop.

Thoughts? Is this potentially a compiler bug, or is this to be expected? I'd think in the case of -O optimizations, it would realize that foo(x) and bar(x) return just x.

I didn't expect it to actually "optimize away" the call and completely ignore printing out "The value is" to standard input.

Edit: I compiled this as just g++ source.cpp (-O1/2/3), under Cygwin using GCC 4.5.0. The -OX versions actually loop infinitely without the stack overflowing.

올바른 솔루션이 없습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top