C & C++

C & C++

Made by DeepSource

Iteration expression is outside of for loop CXX-W1240

Anti-pattern
Minor

The following is the syntax of a for loop.

attr(optional) for ( declaration-or-expression(optional) ; condition(optional) ; iteration-expression(optional) ) statement

Though the last part of the loop i.e. "iteration-expression" is optional, missing it out or moving it to the body of the for loop defeats the purpose of using a for loop.

If such is the requirement, consider using a while.

Bad practice

int main(int argc, char** argv) {
    for (int i = 0; i < argc - 1; /* missing iter-expr */) {
        printf("arg %d of %d", i, argc);
        i++; // bad
    }
}

Recommended

int main(int argc, char** argv) {
    for (int i = 0; i < argc - 1; i++) {
        printf("arg %d of %d", i, argc);
    }
}
int main(int argc, char** argv) {
    int i = 0; 
    while (i < argc - 1) {
        printf("arg %d of %d", i, argc);
        i++;
    }
}