...
This noncompliant code example declares the variable y
as a static int. The value of test( x)
is assigned to y
within the test(int x)
function. However, when test(int x)
is called with an input which results in reaching the initialization of y
more than once, such as the value 12, undefined behavior occurs. Note that this code does not present an infinite recursion and still causes the undefined behavior mentioned.
Code Block | ||
---|---|---|
| ||
int test(int x){ x--; if(x < 0 || x > 10) { return 0; } else { static int y = test(x); //<--undefined behavior occurs here return y; } } |
...
The behavior observed from running this code under various compilers differs.
In gcc3, this code will recurse as if y
were a non-static variable.
In gcc4, upon reaching the initialization of y
for the second time, the program will terminate with the following message:
Code Block |
---|
terminate called after throwing an instance of
'__gnu_cxx::recursive_init'
what(): N9__gnu_cxx14recursive_initE
Aborted (core dumped)
|
Compliant Solution (p
with Block Scope)
...