-2

I am working on sizeof()

when I entered argument as char data type

J=sizeof(char);

It gives output as 1.

But when I entered argument like this

J=sizeof('A');

I am getting output as 4.

Since it's argument is of char data type it should return 1 as output why it is returning 4/2 (Depending upon 32bit/64bit device).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Code Maniac
  • 37,143
  • 5
  • 39
  • 60

2 Answers2

6

In C, 'A' is not a constant of type char, it is an int type. (In C++ it is a char.)

C is a model of consistency in this respect; cf. C++ where 'a' + 'b' is an int type as is a multicharacter constant like 'ab'.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
5

It seems you mean C.

In C character literals (called in C character constants) have type int. So sizeof( 'A' ) is equivalent to sizeof( int ) and yields usually 4.

From the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int.

While sizeof( char ) is alwasy equal to 1.

From the C Standard (6.5.3.4 The sizeof and alignof operators)

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1....

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335