Microsoft KB Archive/31510

= INFO: Bitwise Complement Operator Appears to Fail on Comparison =

Article ID: 31510

Article Last Modified on 7/5/2005

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 5.0 Standard Edition
 * Microsoft Visual C++ 6.0 Service Pack 5

-



This article was previously published under Q31510





SUMMARY
The bitwise complement operator (~) appears to work incorrectly when an application uses it to compare unsigned characters. Before the compiler uses the bitwise complement operator, it performs the &quot;usual arithmetic conversions&quot; which are described in detail in the &quot;C Language Reference&quot; manual. Cast the complemented operand to an unsigned character. This prevents the compiler from performing the arithmetic conversions. The following code example returns the value &quot;failed&quot; even though it appears that values &quot;j&quot; and &quot;~i&quot; should be the same.

Sample Code
/* * Compile options needed: none */


 * 1) include 

main {  unsigned char i = 4; unsigned char j = ~i;

if (j == ~i) printf(&quot;passed\n&quot;); else printf(&quot;failed\n&quot;); } The compiler performs the following four steps to evaluate the expression &quot;if (j == ~i)&quot;:
 * 1) The compiler converts the operand &quot;i&quot; to an unsigned integer.
 * 2) The compiler complements the bits of this unsigned integer. On systems that use 16-bit integers, the high byte becomes 0xFF; on systems that use 32-bit integers, the three high bytes become 0xFFFFFF.
 * 3) The compiler converts the operand &quot;j&quot; to an unsigned integer. On systems that use 16-bit integers, the high byte becomes 0x00; on systems that use 32-bit integers, the three high bytes become 0x000000.
 * 4) The compiler compares the two operands.

The comparison fails because the high bytes of the operands differ.

To work around this situation, modify the comparison as follows:

  if (j == (unsigned char)~i)

Additional query words: 8.00 8.00c 9.00

Keywords: kbinfo kbcompiler KB31510

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.