Reputation: 27581
Cleaning code from warning after adding -O2 -Wall flags to gcc (4.4.6). I have a lot of warning in some legacy code. This is very simplified version to demonstrate the problem:
1 #include <cstdio>
2
3 bool init(bool& a)
4 {
5 return true;
6 }
7
8 int main()
9 {
10 bool a;
11
12 if (!init(a))
13 {
14 return 1;
15 }
16
17 if (a)
18 {
19 printf("ok\n");
20 }
21 }
When compiling it as "gcc main.cpp -O2 -Wall" I receive:
main.cpp:17: warning: `a' is used uninitialized in this function
In real code, init() returns true only if it initializes "a", so there's virually no use by uninitialized "a".
Whan can be done to fix the warning.
Upvotes: 8
Views: 57404
Reputation: 56863
If you don't want to initialize the variable with some value, you can use GCC's diagnostic pragmas:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
if( a )
#pragma GCC diagnostic pop
This might be handy if your code has performace issues when everything would be initialized. In your example, of course, using bool a = false;
is clearly the better choice.
Upvotes: 13
Reputation: 1445
change bool a;
to bool a = false;
will remove this warning.
The compiler wont know init(a)
is meant to 'initialize a', it only sees the program tries to call a function with a uninitialized variable.
Upvotes: 13