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.
sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.
The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.
Because in C character constants, such as 'a' have the type int . There's a C FAQ about this suject: Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).
NULL in C is defined as (void*)0. Since it's a pointer, it takes 4 bytes to store it. And, "" is 1 byte because that "empty" string has EOL character ('\0').
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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With