INFO: Signed Converted to Unsigned in Comparison with Unsigned

ID: Q68265


The information in this article applies to:


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 "Advanced Programming Techniques" version 6.0 manual on page 422, Section B.1.2. The following program produces warning C4018 "signed/unsigned mismatch" at warning level 3 or 4. Casting of the variables preserves their relationship in the expression.

Sample Code


/* Compile options needed: none
*/ 

#include <stdio.h>

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

   if ( b < a )
      printf( "Signed was converted to unsigned\n");
   else
      printf( "Sign was preserved\n");
} 
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:

Additional query words: 8.00 8.00c 9.00


Keywords          : kbcode kbLangC kbVC100 kbVC150 kbVC200 kbVC400 kbVC500 
Version           : MS-DOS:6.0,6.00a,6.00ax,7.0; OS/2:6.0,6.00a,7.0; WINDOWS:1.0,1.5; WINDOWS NT:1.0,2.0,4.0,5.0
Platform          : MS-DOS NT OS/2 WINDOWS 
Issue type        : kbinfo 

Last Reviewed: July 5, 1999