# Stroustrup Chapter 4, Exercise 5

Discussion in 'C++' started by arnuld, Mar 5, 2007.

1. ### arnuldGuest

here Stroustrup asks to write the smallest and largest values of char,
int, short, long etc.

i do not understand his question. when i will do

sizeof(char), i wil only get one value in /byte/. where are the
smallest and largest values of /char/

?

arnuld, Mar 5, 2007

2. ### Guest

On Mar 5, 4:21 pm, "arnuld" <> wrote:
> here Stroustrup asks to write the smallest and largest values of char,
> int, short, long etc.
>
> i do not understand his question. when i will do
>
> sizeof(char), i wil only get one value in /byte/. where are the
> smallest and largest values of /char/

I think he means: "the largest value you can store in a variable of
type char".

If char is signed, then the following might calculate the largest
value if you assume that a byte is 8 bits.
(1<<(sizeof (char)*8-1)-1)

Although, generally, you cannot assume that char is signed. (a non-8-
bit byte seems to me of more academic interest)

Mathieu

, Mar 5, 2007

3. ### mlimberGuest

On Mar 5, 10:21 am, "arnuld" <> wrote:
> here Stroustrup asks to write the smallest and largest values of char,
> int, short, long etc.
>
> i do not understand his question. when i will do
>
> sizeof(char), i wil only get one value in /byte/. where are the
> smallest and largest values of /char/
>
> ?

systems can have different sizes for these types. Write a little
program that prints out the minimum and maximum value of each type.
You can try to calculate them by hand, or you can just use the
constants in <climits> or the functions that are in <limits>. For
instance:

#include <iostream>
#include <climits>
#include <limits>
using namespace std;

int main()
{
cout << "char's min and max on this system are: "
<< CHAR_MIN << " and " << CHAR_MAX;
cout << "char's min and max on this system are: "
<< numeric_limits<char>::min() << " and "
<< numeric_limits<char>::max();
return 0;
}

Cheers! --M

mlimber, Mar 5, 2007
4. ### Michael DOUBEZGuest

arnuld a écrit :
> here Stroustrup asks to write the smallest and largest values of char,
> int, short, long etc.
>
> i do not understand his question. when i will do
>
> sizeof(char), i wil only get one value in /byte/. where are the
> smallest and largest values of /char/ ?

Look for numeric_limits<> templates in STL.
numeric_limits<char>::min()
numeric_limits<char>::max()
etc.

Michael

Michael DOUBEZ, Mar 5, 2007
5. ### mlimberGuest

On Mar 5, 10:33 am, wrote:
> If char is signed, then the following might calculate the largest
> value if you assume that a byte is 8 bits.
> (1<<(sizeof (char)*8-1)-1)
>
> Although, generally, you cannot assume that char is signed. (a non-8-
> bit byte seems to me of more academic interest)

Even if it is mostly an academic issue, I still much prefer to use the
standard macro CHAR_BIT rather than the magic number 8.

Cheers! --M

mlimber, Mar 5, 2007