Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there not any warning on a declaration without initialization in a for loop?

I tried to compile the following code using g++ (gcc version 4.8.2 (Debian 4.8.2-1)), with -Wall flag (adding the -Wextra flag does not change anything for me).

#include <iostream>

using namespace std ;

int main() {
    int i ;
    cout << i << endl ;
}

It gave this warning:

test.cpp: In function ‘int main()’:
test.cpp:7:13: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
    cout << i << endl ;

But the following code does not yield any warning:

#include <iostream>

using namespace std ;

int main() {
    for(int i ; i < 10 ; i++) {
        cout << i << endl ;
    }
}

I did further tests.

The following yields the warning:

#include <iostream>

using namespace std ;

int main() {
    int i ;
    while(i<10) {
        cout << i << endl ;
    }
}

But the following does not:

#include <iostream>

using namespace std ;

int main() {
    int i ;
    while(i<10) {
        cout << i << endl ;
        i++ ;
    }
}

In the above program, if I replace the while by an if, then I have a warning.

Is there some explanation to this? Why can the compiler recognize the problem in some cases and not in others, although they seem very close?

like image 904
Tom Cornebize Avatar asked Oct 20 '22 10:10

Tom Cornebize


1 Answers

Thanks to Pradhan who gave this link, I understood the problem.

This link states the following:

GCC has the ability to warn the user about using the value of a uninitialized variable. Such value is undefined and it is never useful. It is not even useful as a random value, since it rarely is a random value. Unfortunately, detecting when the use of an uninitialized variable is equivalent, in the general case, to solving the halting problem. GCC tries to detect some instances by using the information gathered by optimisers and warns about them when the option -Wuninitialized is given in the command line. There are a number of perceived shortcomings in current implementation. First, it only works when optimisation is enabled through -O1, -O2 or -O3. Second, the set of false positives or negatives varies according to the optimisations enabled. This also causes high variability of the warnings reported when optimisations are added or modified between releases.

Indeed, when I add one of these flags, the compiler yields the warning.

like image 84
Tom Cornebize Avatar answered Oct 22 '22 00:10

Tom Cornebize