Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Visual Studio 2010 warn about unused variables?

#include <string>

using namespace std;

int main()
{
    string s; // no warning
    int i;    // warning C4101

    return 0;
}
  1. Why does Visual Studio warn me about the unused variable i but not about s in the example?
  2. I assume that the compiler is not sure about side effects of the string constructor. Is this the reason for not showing a warning?
  3. Can I somehow enable warnings about unused string variables?

My warning level is set to 4.

like image 598
Fabian Avatar asked Jun 20 '17 07:06

Fabian


2 Answers

I hypothesize that compilers only warn about unused variables for trivially constructible/destructible types.

template<typename>
struct Empty
{

};

template<typename T>
struct Trivial : Empty<T>
{
    int* p;
    int i;
};

template<typename>
struct NonTrivial
{
    NonTrivial() {}
};

template<typename>
struct TrivialE
{
    TrivialE& operator=(const TrivialE&) {}
};

struct NonTrivial2
{
    NonTrivial2() {}
};

struct NonTrivialD
{
    ~NonTrivialD() {}
};

int main()
{
    Empty<int> e;      // warning
    Trivial<int> t;    // warning
    NonTrivial<int> n; // OK
    TrivialE<int> te;  // warning
    NonTrivial2 n2;    // OK
    NonTrivialD nd;    // OK
}

Comparison of compilers' treatment

As can be observed, they are consistent.

Since std::string cannot possibly be trivially destructible, the compilers won't warn about it.

So to answer your question: you can't.

like image 113
Passer By Avatar answered Sep 19 '22 13:09

Passer By


There is no warning because actually there is no unused variable s. s is an instance of the string class and this class has a constructor which is called upon the declaration string s;, therefore s is used by it's constructor.

like image 27
Jabberwocky Avatar answered Sep 20 '22 13:09

Jabberwocky