views:

1553

answers:

5

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?

+7  A: 

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.

luiscubal
A smart compiler would not allocate memory for it. It's probably more to catch bugs/typos.
Zifre
I would think that any reasonable optimizer would not create space for variables that aren't used.
tvanfosson
Thank you. I added a few more reasons I could think of.
luiscubal
+18  A: 

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.

Igor Oks
...or you have an #ifdef somewhere. In the end, that's pretty much the same thing. :)
bk1e
A: 

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.

Zack
+5  A: 

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!!
}
Zifre
+1  A: 

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;
}
no-op
That's what TODO comments are for.
Zifre
No 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.
markh44
Real 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.
Steve Jessop