int i, j;
i = j = 1;
j
is highlighted 开发者_运维技巧by VS 2010 with warning:
The variable is assigned but never used
Why i
is "used" and j
- is not?
An addition with cooperation with Daniel:
int i, j, k, l, m;
i = j = k = l = m = 1;
Only m
is highlighted.
I think it's a bug, It should be in reverse order, =
operator is a right precedent operator according to Microsoft documentation. 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
.
Technically this should be the case for both i
and j
EDIT:
I have again checked the code
int ii, jj;
ii = jj = 1;
using Reflector to generate IL I found
.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.
This is a limitation of the Visual Studio C# compiler. We can't answer because we haven't implemented it.
Original answer
i
is probably used later in your function, while j
isn't.
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.)
I have tried it with Resharper and it's smart enough to give warnings for all variables correctly.
Actually, it is intended behaviour for i
to not be highlighted as a warning, because it is initialised from the value of a variable. 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. According to this post, this is intended (although for a rather questionable reason 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. What flavour of VS2010 are you using? I use Professional at work and Express at home, and find the Express version less accurate with warnings.
精彩评论