4

Why is the output for the following program 4?

#include <stdio.h>

int main()
{
    printf("%d\n", sizeof('3'));
    return 0;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shanpriya
  • 125
  • 2
  • 2
  • 7
  • Because `'x'` literals are `int`s, not `char`s. – cyphar Oct 11 '13 at 12:22
  • This might help: [Size of character ('a') in C/C++](http://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c) – Jost Oct 11 '13 at 12:25
  • @Shanpriya: What prompted you to ask this question? What did you expect this program to output and why? – AnT stands with Russia Oct 12 '13 at 03:36
  • @AndreyT :I thought the declaration as sizeof('3') or sizeof('a') as the values are enclosed within single quotes I thought they mean character would result in output as 1 and not 4. – Shanpriya Oct 12 '13 at 14:31

2 Answers2

10

Because the type of a character constant is int, not char (and the size of int on your platform is four).

The C99 draft specification says:

An integer character constant has type int.

This might seem weird, but remember that you can do this:

const uint32_t png_IHDR = 'IHDR';

In other words, a single character constant can consist of more than one actual character (four, above). This means the resulting value cannot have type char, since then it would immediately overflow and be pointless.

Note: the above isn't a very nice way of doing what it seems to be implying, that's another discussion. :)

unwind
  • 391,730
  • 64
  • 469
  • 606
5

Character literal is int.

In C type of character constant Like '3' is int.

sizeof(character_constant)==sizeof(int)==> In your case sizeof(int)==4

Where As the in C++ it is char

This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.

memset(&i, 'a', sizeof('a'));   // Questionable code 
Gangadhar
  • 10,248
  • 3
  • 31
  • 50