Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, does sizeof measures its result in octet bytes or chars?

Tags:

c

char

sizeof

Although a char is composed of 1 byte on all compilers I know, I was under the impression that C doesn't guarantee the length of a char, it only guarantees that char < short < long. Therefore I assumed that sizeof measures its result in chars in order to abstract from the platform it's running on. To make it more general, I thought that size_t is defined in terms of char.

But now, as far as I can see searching on google, it appears that sizeof does return its result in bytes.

Was I completely wrong in my assumption or is there more to it than that?

like image 947
octavian Avatar asked Nov 30 '22 11:11

octavian


2 Answers

The unit used by sizeof is the char. One of the axioms of the language is that sizeof(char) == 1.

Hence, for systems where char is larger than 8 bits, sizeof does not measure in 8 bit units.

like image 170
David Heffernan Avatar answered Dec 05 '22 01:12

David Heffernan


The units for sizeof is chars.

However, C defines a byte to be the size of a char, and not the more common usage where a byte equals 8 bits.

If you want to know how many bits a char is, use the CHAR_BIT constant in <limits.h>

like image 23
nos Avatar answered Dec 05 '22 02:12

nos