Reputation: 22074
I was wondering how to reliably determine the size of a character in a portable way. AFAIK sizeof(char) can not be used because this yields always 1, even on system where the byte has 16 bit or even more or less.
For example when dealing with bits, where you need to know exactly how big it is, I was wondering if this code would give the real size of a character, independent on what the compiler thinks of it. IMO the pointer has to be increased by the compiler to the correct size, so we should have the correct value. Am I right on this, or might there be some hidden problem with pointer arithmetics, that would yield also wrong results on some systems?
int sizeOfChar()
{
char *p = 0;
p++;
int size_of_char = (int)p;
return size_of_char;
}
Upvotes: 1
Views: 256
Reputation:
There's a CHAR_BIT
macro defined in <limits.h>
that evaluates to exactly what its name suggests.
IMO the pointer has to be increased by the compiler to the correct size, so we should have the correct value
No, because pointer arithmetic is defined in terms of sizeof(T)
(the pointer target type), and the sizeof
operator yields the size in bytes. char
is always exactly one byte long, so your code will always yield the NULL
pointer plus one (which may not be the numerical value 1
, since NULL
is not required to be 0).
Upvotes: 7
Reputation: 399743
I think it's not clear what you consider to be "right" (or "reliable", as in the title).
Do you consider "a byte is 8 bits" to be the right answer? If so, for a platform where CHAR_BIT
is 16, then you would of course get your answer by just computing:
const int octets_per_char = CHAR_BIT / 8;
No need to do pointer trickery. Also, the trickery is tricky:
On an architecture with 16 bits as the smallest addressable piece of memory, there would be 16 bits at address 0x00001, another 16 bits at address 0x0001, and so on.
So, your example would compute the result 1, since the pointer would likely be incremented from 0x0000 to 0x0001, but that doesn't seem to be what you expect it to compute.
1 I use a 16-bit address space for brevity, it makes the addresses easier to read.
Upvotes: 6
Reputation: 24576
The size of one char (aka byte ) in bits is determined by the macro CHAR_BIT
in <limits.h>
(or <climits>
in C++).
The sizeof
operator always returns the size of a type in bytes, not in bits.
So if on some system CHAR_BIT
is 16 and sizeof(int)
is 4, that means an int has 64 bits on that system.
Upvotes: 2