Confusing behavior of sizeof with chars

  • A+
#include <stdio.h> #include <string.h>  int main(void) {     char ch='a';      printf("sizeof(ch)          = %zu/n", sizeof(ch));     printf("sizeof('a')         = %zu/n", sizeof('a'));     printf("sizeof('a'+'b'+'C') = %zu/n", sizeof('a'+'b'+'C'));     printf("sizeof(/"a/")       = %zu/n", sizeof("a")); } 

This program uses sizeof to calculate sizes. Why is the size of 'a' different from the size of ch (where ch='a')?

sizeof(ch)          = 1 sizeof('a')         = 4 sizeof('a'+'b'+'C') = 4 sizeof("a")         = 2 


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.

  1. ch is defined to be of char type, so , pretty straightforward.

  2. In C, sizeof('a') is the same as sizeof (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.

  3. sizeof is a compile-time operator, so the type of the expression is used. As earlier , all the integer character constants are of type int, so int + int + int produces int. So the type of the operand is taken as int.

  4. "a" is an array of two chars, 'a' and 0 (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 two char elements.

That said, finally, sizeof produces a result of type size_t, so you must use %zu format specifier to print the result.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: