...
Noncompliant Code Example (static variables)
The variable maximum is declared as a static variable outside of the function findArrayMax although it is not necessary. Thus, maximum may not be properly initialized and findArrayMax may not work as intended if called more than once. Additionally, if any other part of the program modifies maximum then it may cause faulty behavior in findArrayMax.
| Code Block | ||
|---|---|---|
| ||
static int maximum;
/* function finds max value in an array of ints */
public function findArrayMax(int *values){
...
if(values[i] > maximum){
maximum = values[i];
}
...
}
|
Compliant Solution
The maximum variable maximum is declared as a static variable outside of the function findArrayMax although it is not necessary. Thus, maximum may not be properly initialized and findArrayMax may not work as intended if called more than once. Additionally, if any other part of the program modifies maximum then it may cause faulty behavior in findArrayMax.
...
's scope is only in the function that uses it. As a result, it is properly initialized each time the function is called. This also removes the possibility that another part of the program can modify the variable and alter the function's operations.
| Code Block | ||
|---|---|---|
| ||
/* function finds max value in an array of ints */
public function findArrayMax(int *values){
int maximum = INT_MIN;
...
if(values[i] > maximum){
maximum = values[i];
}
...
}
|
...
Noncompliant Code Example (for-loop counters)
...