C & C++

C & C++

Made by DeepSource

Side effect in array index CXX-W1247

Anti-pattern
Minor

A side effect refers to a modification of the state of a program or system that is outside the intended computation.

Having a side-effect in an array index have multiple drawbacks. Array index with side effect(s) can be difficult to read and understand, especially for other programmers who may need to maintain or modify the code in the future. It can also make debugging more difficult. It can also be difficult to predict the exact outcome of the expression which can lead to unintended consequences and bugs in the program.

Avoid side effects when indexing arrays, as such code reduces readability. Consider breaking the index operation into multiple statements instead.

Bad practice

int x = 0;
int items[10] = {};
while (x < 10) {
    int item = items[x++];
}

Recommended

int x = 0;
int items[10] = {};
while (x < 10) {
    int item = items[x];
    x++;
}