5

My question is about the sizeof operator in C.

sizeof('a'); equals 4, as it will take 'a' as an integer: 97.

sizeof("a"); equals 2: why? Also (int)("a") will give some garbage value. Why?

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • 2
    char vs. integer vs. string :) "sizeof('a')" happens to be promoted to "sizeof (int)". And I'm guessing you already know why "a\0" is "2" :) And I guess you'll understand why (int)(SOME-STRING-ADDRESS) will appear as "garbage" :) – paulsm4 Sep 10 '12 at 18:14
  • I would have thought sizeof('a') == 1 [same as sizeof(char) == 1] and sizeof("a") == 4 [same as sizeof(char *) == 4]. Interesting. – 001 Sep 10 '12 at 18:17
  • 2
    @Johnny Mopp: [Why are C character literals ints instead of chars?](http://stackoverflow.com/questions/433895/why-are-c-character-literals-ints-instead-of-chars) – paulsm4 Sep 10 '12 at 18:32
  • possible duplicate of [sizeof('z') result unexpected](http://stackoverflow.com/questions/6163776/sizeofz-result-unexpected) – Jens Gustedt Sep 10 '12 at 18:54
  • @Jens Gustedt - not a duplicate. The OP is asking two other (directly related, entirely relevant!) things besides "sizeof (character literal)". IMHO... – paulsm4 Sep 10 '12 at 19:21
  • @paulsm4, I know, I meant this more as an incentive to do some research before asking here. – Jens Gustedt Sep 10 '12 at 20:57

2 Answers2

23

'a' is a character constant - of type int in standard C - and represents a single character. "a" is a different sort of thing: it's a string literal, and is actually made up of two characters: a and a terminating null character.

A string literal is an array of char, with enough space to hold each character in the string and the terminating null character. Because sizeof(char) is 1, and because a string literal is an array, sizeof("stringliteral") will return the number of character elements in the string literal including the terminating null character.

That 'a' is an int instead of a char is a quirk of standard C, and explains why sizeof('a') == 4: it's because sizeof('a') == sizeof(int). This is not the case in C++, where sizeof('a') == sizeof(char).

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • 7
    I know the question is tagged C, but I think it's valuable to point out that in C++ `sizeof('a') == 1` (one of the breaking changes between C and C++). – Michael Burr Sep 10 '12 at 19:21
4

because 'a' is a character, while "a" is a string consisting of the 'a' character followed by a null.

MJB
  • 7,639
  • 2
  • 31
  • 41