Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and C++ difference in sizeof('x') [duplicate]

Tags:

c++

c

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.

like image 344
doron Avatar asked Sep 08 '10 23:09

doron


People also ask

What is the difference between sizeof (* A and sizeof A in C?

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.

What does sizeof() do in c++?

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.

Why is sizeof a 4?

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).

What is the size of null string in C?

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').


1 Answers

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++)

like image 198
Cubbi Avatar answered Oct 14 '22 22:10

Cubbi