Indirect recursion, dependent static variables

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

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

There is tmp 5 in VS2012, but I'm not sure if this is guaranteed by the standard.

+6
source share
2 answers

This behavior is undefined.

[statement.decl] / 4

If the control re-enters the declaration recursively during variable initialization, the behavior is undefined. [Example:

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

- end of example]

+10
source

This should not lead to anything useful from any compiler. This is infinite recursion and will most likely result in a segmentation error or when the stack overflows (depending on the system), even if you fix the undefined behavior when you try 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 } 
+2
source

Source: https://habr.com/ru/post/956753/


All Articles