user98188
user98188

Reputation:

Why do I get an "Unreferenced Local Variable" warning? (C++)

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?

Upvotes: 2

Views: 51453

Answers (6)

frediano
frediano

Reputation: 31

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.

Upvotes: 0

Zifre
Zifre

Reputation: 26998

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!!
}

Upvotes: 17

no-op
no-op

Reputation: 131

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;
}

Upvotes: 2

Zack
Zack

Reputation: 2341

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.

Upvotes: 0

Igor
Igor

Reputation: 27250

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.

Upvotes: 28

luiscubal
luiscubal

Reputation: 25121

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.

Upvotes: 23

Related Questions