TL;DR – sizeof
works on the type of the operand.
sizeof(ch)
==sizeof (char)
——————-(1)sizeof('a')
==sizeof(int)
——————–(2)sizeof ('a'+ 'b' + 'c')
==sizeof(int)
—(3)sizeof ("a")
==sizeof (char [2])
———-(4)
Let’s see each case now.
-
ch
is defined to be ofchar
type, so , pretty straightforward. -
In C,
sizeof('a')
is the same assizeof (int)
, as a character constant has type integer.Quoting
C11
,An integer character constant has type
int
. […]In C++, a character literal has type
char
. -
sizeof
is a compile-time operator (except when the operand is a VLA), so the type of the expression is used. As earlier , all the integer character constants are of typeint
, soint
+int
+int
producesint
. So the type of the operand is taken asint
. -
"a"
is an array of twochar
s,'a'
and0
(null-terminator) (no, it does not decay to pointer to the first element of the array type), hence the size is the same as of an array with twochar
elements.
That said, finally, sizeof
produces a result of type size_t
, so you must use %zu
format specifier to print the result.