Question

Here is a sample code:

#include <stdio.h>

int main() {
    int n = 5;
    float v[n];
    float sum;
    int i;

    for(i = 0; i < n; i++) {
        v[i] = i + 1;
        printf("v[%d]=%f\n", i, v[i]);
    }

    for(i = 0; i < n; i++) {
        sum += v[i]; //uninitialized using
    }

    printf("sum=%f\n", sum);

    return 0;
}

gcc compiles it without any warning of uninitialized variable.

I'm using gcc 4.6.3 with following options:

gcc -Wall  main.c -o main

What option should I use to get warning?

Was it helpful?

Solution

Use the -O (optimize) option; value tracking is only performed on optimized code.

$ gcc -Wall -O x.c
x.c: In function ‘main’:
x.c:15: warning: ‘sum’ is used uninitialized in this function

OTHER TIPS

As an aside to @Jens answer, if you compile with -Wall -Wextra -pedantic -O you will see more warnings:

gcc -Wall -Wextra -pedantic -O -o main main.c
main.c: In function 'main':
main.c:5: warning: ISO C90 forbids variable-size array 'v'
main.c:15:20: warning: C++ style comments are not allowed in ISO C90
main.c:15:20: warning: (this will be reported only once per input file)
main.c:15: warning: 'sum' is used uninitialized in this function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top