[英]The variable is assigned but never used
int i, j;
i = j = 1;
j
is highlighted by VS 2010 with warning: j
由VS 2010突出显示并发出警告:
The variable is assigned but never used
变量已分配但从未使用过
Why i
is "used" and j
- is not? 为什么
i
被“使用”而j
不是?
An addition with cooperation with Daniel: 与丹尼尔合作的补充:
int i, j, k, l, m;
i = j = k = l = m = 1;
Only m
is highlighted. 仅突出显示
m
。
I think it's a bug, It should be in reverse order, =
operator is a right precedent operator according to Microsoft documentation. 我认为这是一个错误,它应该是相反的顺序,
=
运算符是根据Microsoft文档的正确的先行运算符 。 So when we have i = j = 1 it should parse it as i = (j = 1) in this case value of j
used to initialize i
so the compiler should say i
initiated but never used, not j
. 因此,当我们有i = j = 1时,它应该将其解析为i =(j = 1),在这种情况下
j
值用于初始化i
因此编译器应该说i
启动但从未使用过,而不是j
。
Technically this should be the case for both i
and j
从技术上讲,这应该是
i
和j
EDIT: 编辑:
I have again checked the code 我再次检查了代码
int ii, jj;
ii = jj = 1;
using Reflector to generate IL I found 使用Reflector生成IL我发现
.maxstack 2
.locals init (
[0] int32 ii,
[1] int32 jj)
L_0000: nop
L_0001: ldc.i4.1 //pushes the integer value of 1 onto the evaluation stack
L_0002: dup //copies the current topmost value on the evaluation stack, and then pushes the copy
L_0003: stloc.1
L_0004: stloc.0
L_0005: ret
From this, it would make it seem that 1 is assigned to ii, and then ii is copied to jj. 由此,它似乎将1分配给ii,然后将ii 复制到jj。
This is a limitation of the Visual Studio C# compiler. 这是Visual Studio C#编译器的限制。 We can't answer because we haven't implemented it.
我们无法回答,因为我们尚未实施。
Original answer 原始答案
i
is probably used later in your function, while j
isn't. i
可能会在你的函数中使用,而j
则不是。
To remove the "probably", you should post the whole function. 要删除“可能”,您应该发布整个功能。 ( Update: This is not true. The whole code inside main is what the OP posted.)
( 更新:这不是真的。主要内部的整个代码是OP发布的内容。)
我已经用Resharper尝试了它,它足够聪明,可以正确地给出所有变量的警告。
Actually, it is intended behaviour for i
to not be highlighted as a warning, because it is initialised from the value of a variable. 实际上,
i
是不将其突出显示为警告,因为它是根据变量的值初始化的。 This warning is only ever given when the variable is assigned from a compile-time constant. 仅在从编译时常量指定变量时才会发出此警告。
Try out the following code: 试试下面的代码:
int i = 0;
string s = "string";
string t = "another string";
string u = t;
var v = new string('v', 1);
var y = new XElement("hello");
Only i
and s
are given warnings. 只有
i
和s
被给予警告。 According to this post , this is intended (although for a rather questionable reason IMO). 根据这篇文章 ,这是有意的(尽管IMO有一个相当可疑的原因)。
So really the mystery here is why there are any warnings at all! 所以真正神秘的是为什么会有任何警告!
I tried this on Visual Studio 2010 Professional and got no such warning. 我在Visual Studio 2010 Professional上试过这个并没有得到这样的警告。 What flavour of VS2010 are you using?
您使用的VS2010有什么味道? I use Professional at work and Express at home, and find the Express version less accurate with warnings.
我在工作中使用Professional,在家中使用Express,并且发现Express版本不太准确并带有警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.