1

Possible Duplicate:
Size of character ('a') in C/C++

Can someone explain why in C sizeof(char) = 1 and sizeof(name[0]) = 1 but sizeof('a') = 4?

name[0] in this case would be char name[1] = {'a'};

I've tried to read through C's documentation to get this but I simply don't get it! if sizeof('a') and sizeof(name[0]) were both 4 I would get it, if they were both 1 that would make sense... but I don't get the discrepancy!

Community
  • 1
  • 1
Ali
  • 12,354
  • 9
  • 54
  • 83

2 Answers2

6

In C, character literals such as 'a' have type int, and hence sizeof('a') is equal to sizeof(int).

In C++, character literals have type char, and thus sizeof('a') is equal to sizeof(char).

References:

C99 Standard: 6.4.4.4 Character constants
Para 2:

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in ’x’ or ’ab’.

C++03 Standard: 2.13.2 Character literals
Para 1:

A character literal is one or more characters enclosed in single quotes, as in ’x’, optionally preceded by the letterL, as in L’x’. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

In c, sizeof operator consider 'a' as integer so you are getting 4 as a size

mcacorner
  • 1,304
  • 3
  • 22
  • 45