Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 that 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
bgColor#FFCCCC
langcpp
int test (int x) {
  x--;
  if (x < 0 || x > 10) {
    return 0;
  }
  else {
    static int y = test(x);  //<--undefined behavior occurs here
    return y;
  }
}

...

Wiki Markup
In this compliant solution, {{y}} is declared before being assigned a value. According to \[[ISO/IEC 14882-2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 6.7.4, the initialization of {{y}} will have been completed at the end of the declaration and before the assignment of a value, consequently removing the possibility of undefined behavior.

Code Block
bgColor#ccccff
langcpp
int test (int x) {
  x--;
  if (x < 0 || x > 10) {
    return 0;
  }
  else {
    static int y;
    y = test(x);  
    return y;
  }
}

...