cmemorycharactersizeof

What's the difference between these two uses of sizeof() in C?


If I do sizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare a char variable and initialize it like so:

  char val = 'r';
  printf("%d\n", sizeof(val));

The output indicates that 'r' only requires 1 byte in memory.

Why is this so?


Solution

  • This is because the constant 'c' is interpreted as an int. If you run this:

    printf("%d\n", sizeof( (char) 'c' ) );
    

    it will print 1.