Violet
Violet

Reputation: 505

Why does this code trigger gcc's "maybe uninitialized" warning?

In plenty of other instances, gcc seems to be able to detect that the condition at the beginning of the loop initializes the variable. It even works if I drop the increment operator. It also goes away without the -02 flag. I've learned to trust that compiler warnings usually do mean something is wrong, so I'm wondering if there's something I'm missing or if it's just a weird compiler quirk.

void act(char **);

void test(int width, int height){
    char * rowA[width];
    char ** A;

    for (int i = 0; i < width * height; ++i){
        if (!(i % width)){
            if (i){
                act(rowA);
            }
            rowA[0] = 0;
            A = rowA;
        }
        *A++ = "hello";
    }
}

Compiling on gcc-6.3.0 with -Wall -Werror -02

Edit: to avoid confusion I've altered the code to be closer to the actual use case.

Upvotes: 2

Views: 1082

Answers (1)

M.M
M.M

Reputation: 141574

The warning means that the compiler couldn't prove the variable was always initialized before use.

This particular warning cannot be perfectly accurate of course, and it errs on the side of caution in that it does raise the warning if it wasn't sure. When using this warning it is common to get this sort of situation where you have to modify your correct code to make the warning go away.

Possibly it is also evidence of an optimizer bug; the optimizer should realize that if(!(i % argc)) can be optimized to if (i == 0).

Upvotes: 2

Related Questions