Microsoft KB Archive/68389

= INFO: sizeof(char Expression) Same as sizeof(int) =

Article ID: 68389

Article Last Modified on 7/5/2005

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 5.0 Standard Edition
 * Microsoft Visual C++ 6.0 Service Pack 5

-



This article was previously published under Q68389





SUMMARY
In Microsoft C/C++, expressions involving variables of type &quot;char&quot; are promoted to type &quot;int&quot;.



MORE INFORMATION
This is ANSI-specified behavior. Below is Section 3.3.7 from the ANSI specifications, which details the semantics of the shift operator:

Semantics

The integral promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width in bits of the promoted left operand, the behavior is undefined.

This means that chars are promoted to integers by default. If you really want a char result, you must cast the final result.

The ANSI-specified semantics of all operators specify promotion from char to int, so the size of any char expression will be the sizeof int. This was also the case for Kernighan and Ritchie (K & R) C.

The sizes of the int and long expressions stay the same because no promotion takes place.

Note that if int is the same size as long rather than short in this implementation, the sizeof both a short expression and a char expression will be 4, as will be the sizeof both an int and a long expression.

Sample Code
/* Compile options needed: none


 * 1) include 

void main(void) {  short si; long li; char sc; unsigned char uc;

printf(&quot;Signed char width: %d\n&quot;,          sizeof((char)(sc<<1)));          // 1 byte

printf(&quot;Signed char width: %d\n&quot;,          sizeof(sc<<1));                 // 2 bytes

printf(&quot;Unsigned char width: %d\n&quot;,          sizeof((unsigned char)uc<<1));  // 2 bytes

printf(&quot;Unsigned char width: %d\n&quot;,          sizeof(uc<<1));                 // 2 bytes

printf(&quot;Short width: %d\n&quot;,          sizeof(si<<1));                 // 2 bytes

printf(&quot;Long width: %d\n&quot;,          sizeof(li<<1));                 // 4 bytes }

Additional query words: 8.00 8.00c 9.00

Keywords: kbinfo kbcode kbcompiler KB68389

-

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

© Microsoft Corporation. All rights reserved.