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

46,842

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;
}
Share:
46,842
Admin
Author by

Admin

Updated on November 12, 2020

Comments

  • Admin
    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
    Venedictos about 15 years
    A smart compiler would not allocate memory for it. It's probably more to catch bugs/typos.
  • tvanfosson
    tvanfosson about 15 years
    I would think that any reasonable optimizer would not create space for variables that aren't used.
  • Venedictos
    Venedictos about 15 years
    That's what TODO comments are for.
  • bk1e
    bk1e about 15 years
    ...or you have an #ifdef somewhere. In the end, that's pretty much the same thing. :)
  • markh44
    markh44 about 15 years
    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.
  • Steve Jessop
    Steve Jessop about 15 years
    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.
  • Matt Montag
    Matt Montag over 12 years
    I kinda like this, because a "forgotten stub" is similar to a "forgotten variable".