Why do I get an "Unreferenced Local Variable" warning? (C++)
Solution 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.
Solution 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.
Solution 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!!
}
Solution 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;
}
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on November 12, 2020Comments
-
Admin over 3 years
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?
-
Venedictos about 15 yearsA smart compiler would not allocate memory for it. It's probably more to catch bugs/typos.
-
tvanfosson about 15 yearsI would think that any reasonable optimizer would not create space for variables that aren't used.
-
Venedictos about 15 yearsThat's what TODO comments are for.
-
bk1e about 15 years...or you have an #ifdef somewhere. In the end, that's pretty much the same thing. :)
-
markh44 about 15 yearsNo flaming required, I like that and have done it myself, although I tend not to check them in. I use them as a reminder to come back to something before checking in and I usually have TODO in the name though so they appear in a TODO search. You need to make sure they don't hang around too long or have too many of them otherwise you end up with a mess.
-
Steve Jessop about 15 yearsReal programmers compile with -Werror ;-) (except when using containers of containers on gcc 3ish: stupid warnings in the standard library...). Seriously, though, the reason I don't like relying on warnings is that you only see them once the first time you compile the file. Then if you don't change it, you never see them again until you've checked in and they show up in the build logs. Oops.
-
Matt Montag over 12 yearsI kinda like this, because a "forgotten stub" is similar to a "forgotten variable".