Inconsistent sizeof Behavior:

130 Views Asked by At

This is the problem of strings chapter from Let Us C book ?

printf("Size of char = %d\n", sizeof(char));
printf("\n%d %d %d", sizeof('3'), sizeof("3"), sizeof(3));

I get this output:

Size of char = 1

4 2 4

I can't understand why the compiler is showing 4 2 4 output while the size of char is 1 in 64-bit C-compiler so according to my logic it should be 1 2 4. Can anyone have a look?

2

There are 2 best solutions below

0
Allan Wind On
  • char by definition is of size 1.
  • '3' is an integer character constant which is of type int. sizeof(int) == 4 on your system.
  • "3" ({'3', '\0'}) is a char [2]. Each char is 1.
  • 3 is also an int.
0
chux - Reinstate Monica On

In C, '3' is an integer character constant.

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'. C11dr §6.4.4.4 2

'3' has type int.

An integer character constant has type int. §6.4.4.4 10


OP has "... so accordig to my logic it should be 1 ...:

Expecting size 1 is not supported by the C spec.
'3' has the size of an int. On OP's platform, that is 4.


[Edit]

OP added printf("Size of char = %d\n" , sizeof(char) ) ;.

sizeof(char) is not relevant to the question as in C, '3' is an int, not a char.


This may differ in other languages.
E.g. In C++, '3' is a char and char have size 1.