Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof('3') == 4 using the GCC compiler? [duplicate]

Tags:

c

char

gcc

sizeof

Why is the output for the following program 4?

#include <stdio.h>

int main()
{
    printf("%d\n", sizeof('3'));
    return 0;
}
like image 434
Shanpriya Avatar asked Dec 06 '22 05:12

Shanpriya


1 Answers

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. :)

like image 167
unwind Avatar answered Dec 16 '22 01:12

unwind