daveagp
daveagp

Reputation: 2669

Better compiler warnings?

Is it possible to add additional warning flags to g++ so that it will warn me about the unitialized b variable in the following code?

#include <iostream>
using namespace std;
int main() {
  int a, b;
  cin >> a;
  while (a>0) b++;
  cout << a;
}

Edit: I forgot to mention that I have tried turning on the flags listed at this other question: Flags to enable thorough and verbose g++ warnings but nothing triggered. ("Tickled!" as I have learned below.)

Upvotes: 1

Views: 858

Answers (2)

user289086
user289086

Reputation:

The option you are after is likely -Wmaybe-uninitialized or -Wuninitialized. Both of these are part of the -Wall option which turns on these, and many other warnings (the -Wxxx options are related to warnings).

Full documentation of the warning options for gcc may be read at: Options to Request or Suppress Warnings in the gcc documentation.

You may also find that -Wextra may be of use to you (either alone, or in conjunction with -Wall). -Wextra also enables -Wuninitialized, but it has other items that are not always set by -Wall and are ones that I like to see (things like -Wunused-parameter and -Wunused-but-set-parameter)... though thats not specific to this bit of code.


That said... (yea, there's a "that said")... I can't seem to tickle an error with this functionality with gcc that is is available on http://gcc.godbolt.org.

Extending your code with some that is specifically described in the documentation for -Wmaybe-uninitialized

#include <iostream>
using namespace std;
int main() {
  int a, b;
  int x, y, z;
  // warning: variable ‘y’ set but not used [-Wunused-but-set-variable]
  cin >> a;
  while (a>0) b++;
  switch(a) {
    case 1: x = 1; y = 1; z++; break;
    // warning: ‘z’ may be used uninitialized in this function [-Wmaybe-uninitialized]
    case 2: x = 4; y = 2; break;
    case 3: x = 5; y = 3;
  }
  cout << a;
  cout << b;
  cout << x;
}

This is an attempt to tickle a number of the unused and unitized warnings. I was able to get the z variable to produce the error, but for some reason b++ in that while loop does not generate an error or warning with gcc (tested using gcc 4.9.0).

Warnings with gcc 4.9.0

clang version 3.4.1, however, does produce warnings with these command line options for both b and z

Warnings with clang 3.4.1

And while -Wall and -Wextra should produce the warnings you are after, for some reason they do not produce the desired warnings for this specific piece of code in gcc 4.9.0

Upvotes: 7

echo
echo

Reputation: 104

Yes!!! You must use -Wuninitialized.

See https://gcc.gnu.org/wiki/Better_Uninitialized_Warnings

Upvotes: 0

Related Questions