Francois Grieu said:
does the expression
(0x41u*0x201)&0x7FFF
yield the well defined value 0x0241, or is the behaviour undefined?
In other words: what's the type of the product on an unsigned by an
int, and does the use of constants make a change ?
There have been a lot of wrong answers in this thread. I'll try very
hard not to generate another one.
The constant 0x41u is of type unsigned int, because of the 'u' suffix.
(Without the 'u', it would be of type signed int.)
The constant 0x201 is of type (signed) int. A hexadecimal integer
constant's type is the first of:
int
unsigned int
long int
unsigned long int
long long int
unsigned long long int
in which its value can be represented; 0x201 (513) is guaranteed to
fit in an int.
0x41u * 0x201 multiplies an unsigned int by a signed int. When two
operands of differing type are multiplied, the "usual arithmetic
conversions" are first applied. The rules take about a page of text
to describe fully. In this case, the signed int operand is implicitly
converted to type unsigned int.
The result of 0x41u * 0x201 has the value 33345 (0x8241) and the type
unsigned int. Since unsigned int is guaranteed to be able to
represent values in the range 0 to 65535, the result is representable
directly as an unsigned int; no wraparound is necessary. (33345 might
overflow a signed int, but that's not relevant here.)
The constant 0x7FFF (32767) is of type (signed) int, since its value
is always representable in that type. The "usual arithmetic
conversions" are applied to the operands of the unary "&" operator.
The left operand has value 0x8241 and type unsigned int. The right
operand has value 32767 and type signed int, and is implicitly
converted to unsigned int. The result has the value 0x241 (decimal
577), and type unsigned int.