vipps...@gmail.com wrote:

sophia.ag...@gmail.com wrote:>
I was going through the book "C a software

engineering approach by darnell & Margolis" there was

a section named sign preserving vs value preserving

it is as follows

sign preserving rule:-

when signed and un signed objects meet in an expression,

the result is always unsigned

true

No, it's false. Let's look at the OP's (snipped) example.

"ex:- if a is an unsigned short whose value is 2, then

the expression a - 3 evaluates to a very large un signed

value rather than the signed value of -1"

It depends on whether an unsigned short promotes to int

or to unsigned int, and that depends on whether unsigned

short values can be represented by an int.

If USHRT_MAX <= INT_MAX, then the value is -1, otherwise

unsigned short promotes to unsigned int and the value is

UINT_MAX.

if both operands are unsigned ints, the result is

unsigned,

Unless by ints you mean integers. Arithmetic on two

unsigned short values may be signed or unsigned for

reasons stated above.

so that the expression 2u-3u always evaluates to a

large unsigned value

To be precise, its value is equal to UINT_MAX
1) how valid is the above explanation?

valid.

No, it's invalid. If you've been fooled it's probably

because unsigned short has the same width as unsigned

int on the implementations you've seen.

2)is there any implementation where the int type is

smaller in size when compared to unsigned short and

unsigned char?

No addressable type is smaller than a character type.

The standard has rules on the values that are representable

by types of the same signedness but different rank. It

has rules that the unsigned integer must be able to

represent all the non-negative values of it's signed

counterpart (same rank.)

It does not talk about the byte size of the representations

beyond imposing implicit minimums based on how many value

(and sign) bits are required to support the minimum range.

no, because your 3) is true

No, 3) is not necessarily true.

3)Does the condition

sizeof(short) <= sizeof(int) <= sizeof(long)

[Assuming a mathematical relation, rather than C's <=...]

always holds in ANSI-C ? or is it true for unsigned values ?

yes.

No. The standard allows sizeof(short) sizeof(int). All it

requires is that SHRT_MAX <= INT_MAX and INT_MIN <= SHRT_MIN.

You're not likely to find an implementation where shorts are

larger than ints, but the standard doesn't exclude them.

--

Peter