Re: Type length in bits?
"James Kanze" <james.kanze@gmail.com> schrieb im Newsbeitrag
news:ac3bc85f-aa5d-465b-b0c5-83ab1fac78fa@x18g2000yqe.googlegroups.com...
On Apr 30, 12:25 am, "Alf P. Steinbach /Usenet"
<alf.p.steinbach+use...@gmail.com> wrote:
* Matthias Hofmann, on 29.04.2011 02:55:
So if I understand this correctly, for types "char" and
"signed char", there may be bit patterns that do not
represent numbers, unless "char" is an unsigned type?
Right.
Not for plain char. In C++. (This is, I think, a difference
between C and C++. C allows trapping bit patterns in plain
char. Not that it makes a difference in practice.)
Yes, it does make a difference. Assuming that the standard allows a
conversion from a pointer to any object type to void* and back to char*, the
following two utility functions are legal:
// Converts a pointer of any non-const
// type to a non-const char pointer.
inline char* char_ptr( void* p ) throw()
{ return static_cast<char*>( p ); }
// Converts a pointer of any constant
// type to a constant char pointer.
inline const char* char_ptr( const void* p ) throw()
{ return static_cast<const char*>( p ); }
But what if the value of one byte accessed through such a char pointer is a
trap representation? Then iterating through the bytes of the underlying
object may cause the program to crash!
The answer seems to be using a pointer to unsigned char instead of plain
char, but there is a problem with that, too: 3.9.2/4 guarantees a char* to
have the same representation as a void*, but it does not give such a
guarantee to unsigned char*.
So how do you implement these two utility functions above? If you you a
plain char*, then you may have problems with bit patterns or sign expansion
errors, and if you use an unsigned char, then you have object representation
problems.
But if C++ does in fact not allow trapping bit patterns, then the problem is
solved and plain char should be used! So could you please refer me to the
corresponding section of the standard where I can find such a guarantee?
I can recommend the following links to earlier discussions on this newsgroup
for anyone who wants to delve deeper into this controversy:
About casting from T* to void* and from void* to char*:
http://groups.google.com/group/comp.lang.c++.moderated/msg/be54dcaab13a12c6
About the guarantee of being able to perform a static_cast from a pointer to
void to a pointer to any character type:
http://groups.google.com/group/comp.lang.c++.moderated/msg/81b1187f784d7274
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]