Erik Oomen
Erik Oomen

Reputation: 21

GCC not complaining about uninitialized variable

Why is it that gcc is not complaining about j being uninitialized? If I remove the j += 10 it will actually complain... Compile with -Wall (tested with gcc 4.9 and 5.3).

int main(void)
{
    int i;
    int j;
    int threshold = 100;

    for (i = 0 ; i < 100 ; i++)
    {
        if (j >= threshold)
            break;
        j += 10; /* comment this line to enable uninitialized variable warning */
    }
    return 0;
}

Upvotes: 1

Views: 401

Answers (2)

gnasher729
gnasher729

Reputation: 52622

An optimiser can figure out that the whole loop is pointless, but it is a bit complicated. The loop is pointless because the values of i and j are not used after the loop, and j is used inside the loop only to decide when to break early, which doesn't matter either because the number of iterations of the loop doesn't matter. So in this situation, if you initialised j to a random number, you would get exactly the same result. So the compiler may not issue a warning because nothing harmful will happen.

Obviously you have undefined behaviour, so the whole app could just crash because of the uninitialised variable. But that is up to the compiler, so if that happened, you should get a warning.

Upvotes: 0

Magisch
Magisch

Reputation: 7352

You're likely compiling this at high optimization levels, which cause the loop to be removed for optimization purposes.

So try compiling at -O1 or -O0 even.

If that doesn't make it show up, ensure that you use high warning levels, with -Wall and -pendantic

Upvotes: 1

Related Questions