为什么我会收到“未引用的局部变量”警告?(C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/895020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get an "Unreferenced Local Variable" warning? (C++)
提问by Zifre
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?
我收到一个关于 x 是一个未引用的局部变量的警告(我假设因为我创建了一个变量,然后没有使用它),为什么这会给我一个警告?
回答by Igor Oks
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.
因为通常人们不会故意创建未引用的变量。因此,如果程序中存在未引用的变量,通常表明您在某处存在错误,编译器会警告您。
回答by luiscubal
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.
此外,代码变得肮脏且难以理解,更不用说程序员通常不会定义他们不需要的变量,所以有点“这真的是你的意思吗?” 警告。
回答by Zifre
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!!
}
回答by no-op
As an aside, i surreptitiously throw in unused variables as a quick'n'dirty TODO mechanism while developing code... flame away:
顺便说一句,我在开发代码时偷偷地将未使用的变量作为快速'n'dirty TODO机制扔进去......熄火:
bool doSomething(...)
{
int dontForgetToReplaceStubWithSomethingReal;
return false;
}
回答by frediano
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.
或者,也许他们希望它的构造函数在作用域内时有副作用,而在作用域外时它的析构函数有另一个副作用,并且不希望编译器对人们最了解的意图如此“有用”别人的代码。
回答by Zack
it also lets you know so that if you thinkyou 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.
它还让您知道,如果您认为您正在使用一个变量,而您没有发现。假设是您出于某种原因创建了该变量,并且您可能忘记在某处使用它。