...
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 | ||||
|---|---|---|---|---|
| ||||
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 | ||||
|---|---|---|---|---|
| ||||
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 | ||||
|---|---|---|---|---|
| ||||
public void doStuff(...){
for (size_t i=0; i < 10; i++) {
/* Perform operations */
}
}
|
...