Archived

This topic is now archived and is closed to further replies.

TerranFury

Data types and portability

Recommended Posts

I have a two questions concerning the portability of code: 1 - Is a char defined as 8 bits or as a byte? This of course affects systems with byte sizes other than 8 bits. 2 - Does sizeof(...) return a number of bytes or a number of chars?

Share this post


Link to post
Share on other sites
1) Don''t quote me on this, but I believe that it would depend on your compiler and its settings.

2) It returns the number of bytes that the variable (or data type, whatever the case) in bytes.

Share this post


Link to post
Share on other sites
I understand that the maximum values of all data types are found in limits.h, and that using limits.h should be portable. However, given what you''ve just said, the following should also therefore be portable disregarding very strange hardware that represents integers in something other than two''s compliment form, regardless of byte size or endian-ness:

(1 << (sizeof(long) * CHAR_BIT)) - 1

It should give the maximum value that can be stored by a long. I am right that this is portable?

Share this post


Link to post
Share on other sites
According to Stroustrup, it is guaranteed that a char has at least 8 bits.

He also states that "Sizes of C++ objects are expressed in terms of multiples of the size of a char, so by definition the size of a char is 1."

It seems silly to express sizes in multiples of char, since sizeof(wchar_t) will most likely return 2, even though it represents a single character.

Share this post


Link to post
Share on other sites
quote:
Original post by TerranFury
I have a two questions concerning the portability of code:

1 - Is a char defined as 8 bits or as a byte? This of course affects systems with byte sizes other than 8 bits.

No

quote:
2 - Does sizeof(...) return a number of bytes or a number of chars?

Bytes, though their size isn''t fixed.

I *think* that a char is always the smallest type, and hence a char is always a byte, but I''m not certain. C/C++ really doesn''t have any absolute rules about type sizes; it merely defines relationships; for instance, a long double must be at least a double, but optionally it may store more precision/larger numbers -- but nothing more than that. A long double could simply be the same as a double (and there''s at least one common platform that does just this; Win32 long doubles are standard 64-bit doubles, rather than Win16 long doubles, which used x87''s built-in 80-bit doubles.

Share this post


Link to post
Share on other sites