PRB: Wrong Result from Expression with Mixed Types & Sizeof

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          : kb16bitonly kbCompiler kbCPPonly kbVC 
Version           : 1.50 1.51 1.52
Platform          : WINDOWS

Last Reviewed: July 21, 1997