so************@yahoo.com (Mark Piffer) writes:
ma*********@chello.at (Mark Piffer) wrote in message news:<41*************@news.chello.at>...
[SNIP, SNIP, SNIP!]
[guess mode]
Lets assume an architecture where sizeof long == 4 and sizeof int ==
2. If you want to extract byte #2 (the byte starting at
2^(2*CHAR_BIT)) of the long argument,
[Edit: I assume an unsigned long argument given as macro parameter
'x'] your expression will try to
shift the signed integer constant UCHAR_MAX left 2*CHAR_BIT, which is
equal to the width of int, which is UB following 6.5.7/3.
OTOH, if you have sizeof long == sizeof int and both > 1 and want to
extract the highest byte (i.e. sizeof int - 1), you invoke UB because
you shift a positive signed integer so many places left that it can't
be represented in an int, which will cause UB following 6.5.7/4 (last
sentence).
[/guess mode]
Where do I err?
Sorry to bump this post again, but I didn't get a definitive answer
and I am really interested if my conclusions about the macro
#define GetByte(x, u)\
((x & UCHAR_MAX << u * CHAR_BIT) >> u * CHAR_BIT)
are wrong.
I believe the answer is, it depends on the definition of UCHAR_MAX.
If UCHAR_MAX is defined
#define UCHAR_MAX (255)
or
#define UCHAR_MAX ((int) 255)
or
#define UCHAR_MAX ((unsigned char) 255)
then the conclusions above are correct (in the last case because of
the ANSI "value preserving rule" for promotions, and assuming that
sizeof(int) > sizeof(char) is true). If UCHAR_MAX is defined
#define UCHAR_MAX (255U)
then the conclusion about the case when sizeof(long) > sizeof(int) is
right but the other conclusion is wrong. If UCHAR_MAX is defined
#define UCHAR_MAX (255UL)
then both conclusions are wrong.
Reading 5.2.4.2.1 p1, the type of UCHAR_MAX is the same as an unsigned
char "converted according to the integer promotion rules", which is
like the first two cases above.
Hence, I believe your conclusions are correct.