# Documentation

### This is machine translation

Translated by
Mouseover text to see original. Click the button below to return to the English verison of the page.

## Avoid Overflows in for-Loops

When memory integrity checks are enabled, if the code generator detects that a loop variable might overflow on the last iteration of the `for`-loop, it reports an error.

To avoid this error, use the workarounds provided in the following table.

Loop conditions causing the errorWorkaround
• The loop counter increments by 1

• The end value equals the maximum value of the integer type

• The loop is not covering the full range of the integer type

Rewrite the loop so that the end value is not equal to the maximum value of the integer type. For example, replace:

```N=intmax('int16') for k=N-10:N```
with:
`for k=1:10`

• The loop counter decrements by 1

• The end value equals the minimum value of the integer type

• The loop is not covering the full range of the integer type

Rewrite the loop so that the end value is not equal to the minimum value of the integer type. For example, replace:

```N=intmin('int32') for k=N+10:-1:N```
with:
`for k=10:-1:1`

• The loop counter increments or decrements by 1

• The start value equals the minimum or maximum value of the integer type

• The end value equals the maximum or minimum value of the integer type

The loop covers the full range of the integer type.

Rewrite the loop casting the type of the loop counter start, step, and end values to a bigger integer or to double For example, rewrite:

```M= intmin('int16'); N= intmax('int16'); for k=M:N % Loop body end```
to
```M= intmin('int16'); N= intmax('int16'); for k=int32(M):int32(N) % Loop body end```

• The loop counter increments or decrements by a value not equal to 1

• On last loop iteration, the loop variable value is not equal to the end value

 Note:   The software error checking is conservative. It may incorrectly report a loop as being potentially infinite.

Rewrite the loop so that the loop variable on the last loop iteration is equal to the end value.