PRB: Wrong Result from Expression with Mixed Types & Sizeof

Last reviewed: July 18, 1997
Article ID: Q131060
1.50 1.51 1.52 WINDOWS kbtool kbprb

The information in this article applies to:

   The Microsoft C/C++ Compiler (CL.EXE), included with:
     - Microsoft Visual C++ for Windows, versions 1.5, 1.51, and 1.52

SYMPTOMS

Expressions that use the sizeof operator and values of more than one type can generate the wrong result.

RESOLUTION

Avoid mixed-mode expressions containing the sizeof operator.

STATUS

This behavior is by design. It is in compliance with the rules of ANSI C. The result type of the sizeof operator is size_t, which is defined in STDDEF.H to be unsigned int. Promoting the int to unsigned int causes the problem.

MORE INFORMATION

When compiled with one of the products listed above, the following sample code displays this result:

   Failed: x = 65532

The expected result is this:

   x = -4

Sample Code to Demonstrate Behavior

/* Compile options needed: none
*/
#include <stdio.h>
void main(void)
{
   long x;
//Work-around: comment this line and uncomment the next line
   x = -1*sizeof(long);
   //x = -1*(int)sizeof(long);
   if (x != -4)
      printf("Failed: ");
   printf("x = %ld\n",x);
}


Additional reference words: 1.50 8.00c calculation no32bit
KBCategory: kbtool kbprb
KBSubcategory: CPPiss
Keywords : CPPiss kb16bitonly kbprb kbtool
Version : 1.50 1.51 1.52
Platform : WINDOWS


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: July 18, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.