Why do I get an “Unreferenced Local Variable” warn

2020-05-29 06:34发布

问题:

When I do something like

#include<iostream>
int main()
{
    int x;
    return 0;
}

I get a warning about x being an unreferenced local variable (I assume becuase I created a variable, then did not use it), why does this give me a warning though?

回答1:

Probably because you're wasting memory for nothing.

Besides, the code becomes dirty and harder to understand, not to mention that programmers don't usually define variables they don't need, so it's sort of a "is this really what you meant?" warning.



回答2:

Because usually people don't create unreferenced variables intentionally. So if there is an unreferenced variable in a program, usually it is a sign that you have a bug somewhere, and the compiler warns you about it.



回答3:

It's probably to stop something like this:

void some_func() {
    int a, b, c, d, e;
    ...
    do_something_with(a);
    do_something_with(b);
    do_something_with(c);
    do_something_with(d);
    do_something_with(c); // after hours of reading code, e looks like c: BUG!!
}


回答4:

As an aside, i surreptitiously throw in unused variables as a quick'n'dirty TODO mechanism while developing code... flame away:

bool doSomething(...)
{
    int dontForgetToReplaceStubWithSomethingReal;
    return false;
}


回答5:

it also lets you know so that if you think you are using a variable and are not you will find out. the assumption being that you created the variable for a reason and maybe you forgot to use it somewhere.



回答6:

Or, maybe they expected its constructor to have a side effect when scoped in, and its destructor another side effect when scoped out, and didn't want the compiler to be so 'helpful' with what folks know best when it comes to the intent of other's code.