Question

Is the result of the following indirect recursion defined by the standard or is it undefined behavior?

auto abc() -> int ;

auto xyz() -> int  {
    static int instance = 3 + abc();
    return instance;
}

auto abc() -> int {
    static int instance = 2 + xyz();
    return instance;
}

int main() {
    int tmp = xyz();//or abc();
}

In VS2012 tmp is 5 but I'm not sure if that's guaranteed by the standard.

Was it helpful?

Solution

It's undefined behaviour.

[statement.decl]/4

If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined. [Example:

int foo(int i) {
    static int s = foo(2*i); // recursive call - undefined
    return i+1;
}

end example ]

OTHER TIPS

This should not result in anything useful from any compiler. It is infinite recursion and will likely result in a segmentation fault or a stack overruns heap error (depending on the system), even if you fix the undefined behavior of attempting to recursively set the value of a static variable:

auto abc() -> int;

auto xyz() -> int  
{
    return abc();
}

auto abc() -> int 
{
    return xyz();
}

int main() 
{
    int tmp = xyz(); // defined behavior, but infinite recursion
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top