IL fun fact: not is not ! 1
Picture yourself working on crafting a specific piece of CIL.
You need to write the compiled equivalent of:
bool b = ...; bool n = !b;
It would be tempting to write:
ldloc b not stloc n
Except that it would not always work. not doesn’t negate booleans, it computes the bitwise complement of the value on the stack. It’s also not to be confused with the neg opcode, which negates a value, as in a multiplication by -1.
The usual pattern to negate a boolean is:
ldloc b ldc.i4.0 ceq stloc n
But that’s not really fun, is it?
Actual fun fact: there’s a misused “not” in the ECMA 335 in the example of the section 14.5 of the partition II.
Trackbacks
Use the following link to trackback from your own site:
http://www.evain.net/blog/articles/trackback/1102
I wrote a toy C to CIL compiler a year or two ago. I remember commenting in the code that “logical not” did not seem to exist in CIL. I remember commenting that I would just compare for equality with zero until I figured out the right way to do it. That comment looks pretty silly now. :-)