But i try to assign
char ch = 128;
short int i = 32768;
printf ("ch = %d", ch); \\ prints ch = -128
printf ("ch = %d", i); \\ prints ch = -32768
I got confused after seeing the result. How come it is possible to
print even -128 if minimal range is (-127 ot 127) same applies to
short int ?
It obviously can have more that the minimum range. :-)
On current hardware, it is common to have one extra negative value
giving char a range of -128 to +127. That's affecting the result here.
To be really strict, you are not allowed by the standard to use out of
range values for signed integers. Overflow causes undefined behavior
according to the standard. That allows the implementation to produce
any result it feels like, perhaps displaying the most negative value.
Bo Persson
The book either lies or you did not understand what it did say.
Exact range for char is: std::numeric_limits<char>::min() to
std::numeric_limits<char>::max().
Exact range for short is: std::numeric_limits<short>::min() to
std::numeric_limits<short>::max().
These numeric_limits may differ from platform to platform. Note that
printf is bad thing for such tests since it does not care about type
of arguments. With %d format specifier of printf you get whatever
argument (or slice of it) reinterpreted as int.
C++ data types has lot of dependencies on implementation(platform)
from assigning values to allocating size for each type :)
> I am reading the book "The complete reference C++" i see that minimal
> range of char has been mentioned as -127 to 127
That is incorrect. A char is only guaranteed to be able to hold from 0
to 127, it may hold more of course.
> Suresh V <vsure...@gmail.com> wrote:
>
>> I am reading the book "The complete reference C++" i see that minimal
>> range of char has been mentioned as -127 to 127
>
> That is incorrect. A char is only guaranteed to be able to hold from 0
> to 127,
No. The range is required to be bigger, but that's the range that you can
rely on if you don't want to depend on implementation-defined behavior.
> it may hold more of course.
It will _definitely_ be able to hold more.
That's all a bit muddled. A signed char must be able to hold values
from -127 to 127, inclusive. An unsigned char must be able to hold
values from 0 to 255, inclusive. A char must have the same range and
semantics as one of those two; it's implemenation-defined which one it
is.
Those are, as stated, minimal ranges; larger ranges are allowed.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
Exactly. Like I said, the only range that it is *guaranteed* to hold is
from 0 to 127. CHAR_MIN will be no higher than 0, CHAR_MAX will be no
lower than 127.
If that is the book by Schildt, burn it and buy a good book.
It's full of inaccuracies.
See http://www.accu.org for suggestions on good references.