Reputation: 839
unsigned u = 1;
int i = -u;
Does the 2nd assignment come under 6.5.5: If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
Or does it come under 6.3.1.3: 1 When a value with integer type is converted to another integer type other than _Bool, ... ... 3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
I wrote this question because the following (thanks to R.. for clarifications) generates undefined behaviour under 6.5.5 :
int i = INT_MIN;
i = -i;
The problem with the above is that the expression -i
is of type int
and -INT_MIN
for 2's complement platform may be larger than INT_MAX. Under that context, it generates undefined behaviour.
On the other hand, for:
unsigned u = 1;
int i = -u;
-u
is of type unsigned. As explained in Is unsigned integer subtraction defined behavior? although the range of unsigned is nominally from 0 to UINT_MAX
, there is really no such thing as an out of range unsigned value. So 6.5.5 does not apply for -u
. But we still have the assignment expression i=-u
in which case 6.3.1.3 applies.
Or to put it another way, if I can reword 6.5.5, it would be: If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), if the expression type is not one of the standard or extended unsigned type, the behavior is undefined. If the expression type is one of the standard or extended unsigned type, and the result is less than 0 or greater than the maximum representable value, the result shall adjusted as per 6.3.1.3/2.
Upvotes: 1
Views: 284
Reputation: 215487
It comes under 6.3.1.3. There's nothing exceptional about the expression -u
. It's equal to UINT_MAX
. Assigning the result into a signed type in which the value UINT_MAX
cannot be represented then results in an implementation-defined conversion or signal.
Upvotes: 3