views:

73

answers:

3

Hi, I can't seem to get rid of this warning for the following line of code:

d.word[wrdIndex++] = d.GetWord(english) | (ulong)i;

the warning applies to the code after the assignment operator. the method GetWord returns a ulong. I've tried the following to no avail:

d.word[wrdIndex++] = (d.GetWord(english) | (ulong)i);
d.word[wrdIndex++] = d.GetWord(english) | ((ulong)i);
d.word[wrdIndex++] = ((ulong)d.GetWord(english)) | ((ulong)i);

Anyone have any ideas?

+1  A: 

Sorry, just got rid of it thusly:

ulong w = d.GetWord(english);
ulong u = (ulong)i;
d.word[wrdIndex++] = w | u;
cskilbeck
+5  A: 

You get rid of the warning by first thinking about the warning and deciding if the compiler is right to bring the problem to your attention in the first place! Are you in fact going to get incorrect results from the bitwise or should the conversion from a signed type to a larger unsigned type sign-extend the integer?

If the answer is yes then your solution is wrong. Don't eliminate the warning by tricking the compiler into still doing the wrong thing without giving you the warning. Eliminate the warning by doing the right thing: don't use a conversion that sign-extends the integer.

If the answer is no, and you want the sign extension then your solution or Hans Passant's solution is correct. However, I would put a comment to that effect in the code, because as it stands, it is hard to see that the sign extension is desirable.

Eric Lippert
The code certainly does what it should (and this is the right way to do what I want in this case I think) - I'm just surprised that the 2nd of the 3 attempts : d.GetWord(english) | ((ulong)i) still delivers the warning as the ((ulong)i) is cast to a ulong before the bitwise OR operator is applied, right?
cskilbeck
Ah, now I get it - it's actually pretty clever of the compiler to warn me about this I guess. Is there a way to cast to ulong without sign extension (other than by masking off the top bit manually)?
cskilbeck
cast to uint first. `(ulong)(uint)i`
CodeInChaos
+2  A: 
int i=-1;
ulong u1=(ulong)i;//=18446744073709551615
ulong u1a=(ulong)(long)i;//=18446744073709551615
ulong u2=(ulong)(uint)i;//=4294967295

So a cast from int to ulong corresponds to first sign-extending to (signed) long, and then casting away the sign.

CodeInChaos