Does omitting the "signed" keyword change semantics?

B

BigMan

What is the difference between char and signed char, short and unsigned
short, int and signed int, long and unsigned long?
 
P

Phil Endecott

BigMan said:
What is the difference between char and signed char, short and unsigned
short, int and signed int, long and unsigned long?

Well, obviously, the range of values that they represent is different.
Signed types can represent negative numbers whereaas unsigned types use
the same bit patterns to represent large positive numbers.

But of course C and C++ don't have any run-time checks to stop you from
subtracting 1 from an unsigned 0. So it is tempting to think that the
types are not actually any different since in many common cases, e.g.
when you are doing addition and subtraction, the bit patterns will end
up the same whatever the types.

But there are plenty of places where it does matter. For example, when
you do formatted input/output, conversions (e.g. assign a shorter type
to a longer type - is it sign-extended?), comparisons (is 11111111
greater or less than 00000000?), and so on.

Using the correct types also helps the compiler to give you sensible
warnings.

--Phil.
 
P

Pete Becker

Phil said:
But of course C and C++ don't have any run-time checks to stop you from
subtracting 1 from an unsigned 0.

Nor should they, since the result is well-defined.
 
B

BigMan

Sorry! What I meant was if there is a difference between char and
signed char, short and signed short, int and signed int, long and
signed long. I.e. does int (or char, short, long) means signed int (or
signed char, signed short, signed long respectively)?
 
B

Bob Hairgrove

What is the difference between char and signed char, short and unsigned
short, int and signed int, long and unsigned long?

char, signed char and unsigned char are special cases: they are three
separate types. Most compilers will have a compile parameter enabling
you to influence how plain char is treated -- either as signed or
unsigned. But plain char is a distinct type.

signed int and int, OTOH, are synonymous, as are signed long and long,
signed short and short, etc. IOW, integral types are signed unless you
write unsigned.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top