INFO: Bitwise Complement Operator Appears to Fail on ComparisonLast reviewed: August 26, 1997Article ID: Q31510 |
The information in this article applies to:
SYMPTOMSThe bitwise complement operator (~) appears to work incorrectly when an application uses it to compare unsigned characters.
CAUSEBefore the compiler uses the bitwise complement operator, it performs the "usual arithmetic conversions" which are described in detail in the "C Language Reference" manual.
RESOLUTIONCast the complemented operand to an unsigned character. This prevents the compiler from performing the arithmetic conversions.
MORE INFORMATIONThe following code example returns the value "failed" even though it appears that values "j" and "~i" should be the same.
Sample Code
/* * Compile options needed: none */ #include <stdio.h> main() { unsigned char i = 4; unsigned char j = ~i; if (j == ~i) printf("passed\n"); else printf("failed\n"); }The compiler performs the following four steps to evaluate the expression "if (j == ~i)":
To work around this situation, modify the comparison as follows:
if (j == (unsigned char)~i) |
Additional query words: 8.00 8.00c 9.00
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |