Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sizeof('c') is returning 4 instead of 1? [duplicate]

Tags:

c

Possible Duplicate:
Why are C character literals ints instead of chars?

http://ideone.com/lHYY8

int main(void)
{
        printf("%d %d\n", sizeof('c'), sizeof(char));
        return 0;
}

Why does sizeof('c') return 4 instead of 1?

like image 256
ob_dev Avatar asked Nov 28 '22 17:11

ob_dev


2 Answers

Because in C character constants have the type int, not char. So sizeof('c') == sizeof(int). Refer to this C FAQ

Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).

like image 108
cnicutar Avatar answered Dec 01 '22 06:12

cnicutar


One (possibly even more extreme) oddity that also somehow justifies this, is the fact that character literals are not limited to being single character.

Try this:

printf("%d\n", 'xy');

This is sometimes useful when dealing with e.g. binary file formats that use 32-bit "chunk" identifiers, such as PNG. You can do things like this:

const int chunk = read_chunk_from_file(...);
if(chunk == 'IHDR')
  process_image_header(...);

There might be portability issues with code like this though, of course the above snippet assumes that read_chunk_from_file() magically does the right thing to transform the big-endian 32-bit value found in the PNG file into something that matches the value of the corresponding multi-character character literal.

like image 44
unwind Avatar answered Dec 01 '22 08:12

unwind