INFO: sizeof() Function Returns unsigned Instead of int

Last reviewed: September 4, 1997
Article ID: Q60332

The information in this article applies to:
  • Microsoft C for MS-DOS, versions 6.0, 6.0a, 6.0ax
  • Microsoft C for OS/2, versions 6.0, 6.0a
  • Microsoft C/C++ for MS-DOS and OS/2, versions 7.0
  • Microsoft Visual C++ for Windows, versions 1.0, 1.5
  • Microsoft Visual C++ 32-bit Edition, versions 1.0, 2.0, 4.0, 5.0

SUMMARY

To comply with new ANSI specifications, the sizeof() operator in Microsoft C versions 6.0 and later and QuickC versions 2.5 and later returns an unsigned integer. In C version 5.1 and QuickC version 2.0, this function returns a signed int.

MORE INFORMATION

The change to an unsigned return value can cause problems in code that uses the idiom "-sizeof(type)." The following code example attempts to position the file pointer one record from the end of a file. The method the code demonstrates works with C version 5.1, but fails with C version 6.0 and later.

   fseek(file, (long)(-sizeof(record)), SEEK_END);

This fseek call positions the file pointer far beyond the end of the file because the compiler does not sign extend the generated value. Because the unary minus (-) operator does not change the "signedness" of a variable and the sizeof() operator returns an unsigned int, the compiler performs a zero extension to convert the unsigned int to a long.

In other words, if the record variable was of type char, the following code returns the long value -1 when compiled with C 5.1 and 32,767 when compiled with C 6.0:

   (long)(-sizeof(record))

One method to work around this problem involves casting the result of the sizeof operator to a signed int before negating the value and casting it to a long. For example:

   (long)-(int)sizeof(record)
Keywords          : CLngIss kbfasttip
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


================================================================================


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: September 4, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.