Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc - removing "is used uninitialized in this function" warning

Tags:

c++

linux

gcc

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.

like image 936
dimba Avatar asked Oct 15 '13 05:10

dimba


1 Answers

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.

like image 197
Zac Wrangler Avatar answered Oct 25 '22 01:10

Zac Wrangler