0
#include <stdio.h>
int main()
{
    char c = '0';
    printf("%d %d",sizeof(c), sizeof('0'));
    return 0;
}

I expect the output is 1 1.but the real result is 1 4.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
吴小葱
  • 3
  • 3
  • 3
    `'0'` is an integer. – pmg Jul 30 '19 at 12:15
  • 1
    `sizeof()` returns a `size_t`, which is properly printed with `%zu`. Printing `size_t` with `%d` is undefined behavior. – Andrew Henle Jul 30 '19 at 12:17
  • 1
    You would have been fond of a DSP I once worked with, it had `CHAR_BIT == 16` and `sizeof(char) == sizeof(int)` – on *this* machine, you would have received the output you expected... – Aconcagua Jul 30 '19 at 12:20

3 Answers3

4

Opposite to C++ in C (integer) character constants have the type int.

From the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int.

Compare the quote with the quote from the C++17 Standard (5.13.3 Character literals)

2 A character literal that does not begin with u8, u, U, or L is an ordinary character literal. An ordinary character literal that contains a single c-char representable in the execution character set has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set....

As for this expression

sizeof(c)

then it provides the size of an object of the type char. Objects of the type char always have the size 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....

Pay attention to that a valid call of the function printf will look like

printf("%zu %zu",sizeof(c), sizeof('0'));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

Character literals ('0', 'a', 'd', '.') in C are of type int (unlike in C++, where they are of type char).

So you will get in C:

sizeof(char) == 1
sizeof('0')  == sizeof(int) // note that this is not necessarily 4!

whereas in C++ you will have:

sizeof(char) == 1
sizeof('0')  == sizeof(char)
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
1
sizeof('0')

is actually

sizeof(ASCII value of '0')

which is integer. Thus it is printing sizeof(int).

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44