Microsoft KB Archive/68265

= INFO: Signed Converted to Unsigned in Comparison with Unsigned =

Q68265

-

The information in this article applies to:


 * Microsoft C compiler for MS-DOS, versions 6.0, 6.0a, 6.0ax
 * Microsoft C compiler for OS/2, versions 6.0, 6.0a
 * Microsoft C/C++ compiler for MS-DOS
 * Microsoft C/C++ compiler for OS/2, version 7.0
 * Microsoft Visual C++, versions 1.0, 1.5, 2.0, 4.0

-

SUMMARY
The additional adherence to the ANSI standard, beginning with C version 6.0 and QuickC versions 2.5 and 2.51, will cause a negative signed integer to be converted to an unsigned integer in a comparison with an unsigned integer. This is the correct and intended behavior, although it may produce results that are unexpected. The sample code below demonstrates this behavior.

MORE INFORMATION
This is new in C 6.0 and is documented in the Microsoft C &quot;Advanced Programming Techniques&quot; version 6.0 manual on page 422, Section B.1.2. The following program produces warning C4018 &quot;signed/unsigned mismatch&quot; at warning level 3 or 4. Casting of the variables preserves their relationship in the expression.

Sample Code
/* Compile options needed: none


 * 1) include 

void main( void) {  int a = -1; unsigned b = 1;

if ( b < a ) printf( &quot;Signed was converted to unsigned\n&quot;); else printf( &quot;Sign was preserved\n&quot;); } NOTE: When you compile the program in Visual C++ version 5.0 or 6.0, you may receive the following warning that indicates the type mismatch:

warning C4018: '<' : signed/unsigned mismatch

The output from the program above is:   Signed was converted to unsigned Either of the following methods may be used to achieve the expected behavior:   If you are sure that b is less than 32768, change the if statement to:      if ( (signed int) b <  a)  NOTE: This will produce the most efficient code.   Change the if statement to:      if ( (long) b < (long) a) 

Additional query words: 8.00 8.00c 9.00

Keywords : kbcode kbLangC kbVC100 kbVC150 kbVC200 kbVC400 kbDSupport

Issue type : kbinfo

Technology : kbVCsearch kbVC400 kbAudDeveloper kbZNotKeyword8 kbvc150 kbvc100 kbZNotKeyword3 kbVC200

Last Reviewed: July 22, 2001

-

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

© 2002 Microsoft Corporation. All rights reserved.