V8016. The loop may be executed incorrectly or its condition will never be met. Inspect initial and final values in the 'for' loop.
The analyzer has detected an error in the for loop where the initial and final values of the counter are the same.
This can cause several issues:
- the loop may not iterate at all;
- it may iterate only once;
- it may iterate more times than intended.
Examples for each case:
Example N1. The loop does not iterate:
func processRange(begin int, end int) {
for i := begin; i < begin; i++ {
....
}
}
Before the first loop iteration, the i < begin check is performed. This condition is always false because it checks whether begin < begin.
To fix the issue, use the end parameter in the loop condition:
func processRange(begin int, end int) {
for i := begin; i < end; i++ {
....
}
}
Example N2. The loop iterates once:
func processRange(begin int, end int) {
for i := end; i >= end; i-- {
....
}
}
Before the first iteration, the i >= end check is performed, which is true because the i value matches the end value. Before the second iteration, the i value is decreased by one. The next condition becomes end - 1 >= end, which is false. As a result, the loop iterates only once.
To fix this, change the condition for exiting the loop:
func processRange(begin int, end int) {
for i := end; i >= begin; i-- {
....
}
}
Example N3. The loop iterates more times than intended:
func processRange(begin int, end int) {
for i := end; i >= end; i++ {
....
}
}
Before the first iteration, the i >= end condition is true because i equals end. With each subsequent check, i increases, but end remains unchanged. As a result, the loop will terminate only when the i counter overflows.
To fix this, initialize i using the begin parameter and adjust the exit condition of the loop accordingly:
func processRange(begin int, end int) {
for i := begin; i <= end; i++ {
....
}
}