Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The variable is assigned but never used

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.

like image 203
abatishchev Avatar asked Dec 09 '10 12:12

abatishchev


People also ask

What does it mean when a variable is assigned but never used?

A local variable is defined (by an assignment) but never used. It is sometimes necessary to have a variable which is not used. These unused variables should have distinctive names, to make it clear to readers of the code that they are deliberately not used.

Is assigned but never used C#?

It means you have given answer a value, but not referenced it elsewhere. Meaning you are not using answer elsewhere in your program. You fix it by referencing answer from another part of your program.


2 Answers

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.

like image 167
Saeed Amiri Avatar answered Oct 07 '22 14:10

Saeed Amiri


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.

like image 37
Adriaan Stander Avatar answered Oct 07 '22 13:10

Adriaan Stander