Avoid unconditional jumps within loops. If the loop is intended to repeat but mistakenly contains an unconditional jump, it can result in incorrect program behavior. The loop may terminate prematurely or fail to execute essential iterations, leading to incorrect output or unexpected program states.
When a loop contains an unconditional jump statement, such as a break
or return
statement, it implies that the loop will be executed only once, regardless of any condition or the range of iteration.
This can happen due to a mistake in the code, where the loop was intended to repeat but an incorrect control flow statement was used.
Alternatively, it could be an unnecessary use of a loop when a single execution would have sufficed.
Furthermore, it reduces code readability because other developers who encounter the loop might expect it to execute multiple times based on its structure. This can lead to confusion and make the code harder to understand and maintain.
for (i in 1..10) {
// Some code here
break
}
for (i in 1..10) {
// Some code here
return
}
for (i in 1..10) {
if (i == 5) {
// Some code here
break
}
// Some code here
}