tags:

views:

189

answers:

3

Possible Duplicate:
Why are C character literals ints instead of chars?

Why when using C does sizeof('x') return 4 but sizeof('x') in C++ returns 1?

C++ normally strives to be nothing more than a superset of C so why do the two results diverge?

Edit Just some further clarification. This seems like a deliberate move on the part of the standards committee and I assume changing the size of 'x' would not have been done without a good reason. I am interested in what the reason is.

+3  A: 

Because is C, 'x' is actually an int, while in C++ it's a char.

C++ tries is tighten up strong typing that was a bit lax in C.

James Curran
Intriguing behavior... I'm not much of a C guy but this surprises me. So when you call `printf("%c", 'x');`, 4 bytes are pushed onto the stack for the varargs, but in C++ it would only be 1 byte? How could that work, considering the CRT doesn't know what language is calling it?
tenfour
+1, it's in the spec!
Carl Norum
@tenfour, nope - 4 bytes are pushed in C++ too. varargs calls have lots of type promotion rules.
Carl Norum
@tenfour: In C++ variadic argument always go through integral promotions, meaning that `char` and `short` types are always promoted to `[unsigned] int` before being passed to a variadic function. The same thing happens in C.
AndreyT
learn something every day :) Now I wonder why a char literal is an `int` in C?
tenfour
@tenfour, see http://stackoverflow.com/questions/433895/why-are-c-character-literals-ints-instead-of-chars
Carl Norum
+6  A: 

C++ is not a superset of C. Particularly if you use the "current" versions - a compiler in C++0x mode will choke on C99 code.

kwatford
But that is because the (then) new C99 standard was not incorporated into C++
doron
@deus-ex C99 was out for years before C++0x started. If they wanted to make C a subset, they would have included the changes. In fact, they did include some of them. `#include <cstdint>` refers to C99's `stdint.h`.
kwatford
C and C++ have been diverging slightly with recent versions of standards. I wouldn't expect C99 to be rolled into C++0x or vice versa, with respect to the common feature sets.
John Gaughan
+10  A: 

To quote the C++ standard ISO 14882:2003, annex C.1.1 clause 2.13.2

Change: Type of character literal is changed from int to char

Rationale: This is needed for improved overloaded function argument type matching. For example:

int function( int i );
int function( char c );
function( ’x’ );

It is preferable that this call match the second version of function rather than the first

(annex C describes the incompatibilities between C and C++)

Cubbi
More or less what I thought but nice to see in black and white.
doron
Of course, they *could* have just introduced a "`char` literal" syntax - eg `C'x'` is of type `char`, in the same way that `L'x'` is of type `wchar_t`.
caf
Note, a multicharacter literal eg `'abcd'` *is* still of type `int`, with implementation-defined value.
Potatoswatter