Versions Compared

Key

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

...

In this noncompliant code example, the function counter() increments the global variable count and then returns immediately if this variable exceeds a maximum value.

Code Block
bgColor#ffcccc
langc
unsigned int count = 0;

void counter() {
  if (count++ > MAX_COUNT) return;
  /* ... */

}

...

In this compliant solution, the variable count is declared within the scope of the counter() function as a static variable. The static modifier, when applied to a local variable (one inside of a function), modifies the lifetime (duration) of the variable so that it persists for as long as the program does, and does not disappear between invocations of the function.

Code Block
bgColor#ccccff
langc

void counter() {
  static unsigned int count = 0;
  if (count++ > MAX_COUNT) return;
  /* ... */

}

...

Complying with this recommendation requires that you declare variables where they are used, thus improving readability and reusability. In this example, this would be done by declaring the loop's index variable i within the initialization of the for loop. This was recently relaxed in the C99 standard.

Code Block
bgColor#ccccff
langc
public void doStuff(...){
  for (size_t i=0; i < 10; i++) {
    /* Perform operations */
  }
}

...