int

R

RoSsIaCrIiLoIA

if
{
unsigned u = -INT_MIN;
int i, sign = -1;
i = sign * u;

then i == INT_MIN or not?
 
M

Malcolm

RoSsIaCrIiLoIA said:
if
{
unsigned u = -INT_MIN;
int i, sign = -1;
i = sign * u;

then i == INT_MIN or not?
The calculation is allowed to overflow, producing implementation-defined (I
think) behaviour.
On most platforms, INT_MIN = -INT_MAX - 1. Taking the negative produces
INT_MAX + 1, which will overflow to INT_MIN. Multiplying by -1 will further
overflow to INT_MIN, for by a contorted route you will actually get the
answer you suggest.
 
P

Peter Nilsson

RoSsIaCrIiLoIA said:
if
{
unsigned u = -INT_MIN;

-INT_MIN is performed using signed int arithmetic (before the assignment), and it can
overflow (undefined behaviour).

Note that even if you do...

unsigned u = INT_MIN;
u = -u;

You have no guarantee that u will be the magnitude of INT_MIN. Since UINT_MAX can equal
INT_MAX, you might have u == 0.
int i, sign = -1;
i = sign * u;

then i == INT_MIN or not?

sign * u will be performed in unsigned int arithmetic, so the result will always be
positive. The conversion on assignment to i will be implementation defined if the value is
outside the range [0..INT_MAX]. So, it could theoretically set i to anything. C99 even
allows an implementation defined signal to be raised.

Even C99 (optional) intN_t types, whilst necessarily unpadded twos complement integers,
are not immune from implementation defined conversions and potential signals if assigned a
value that is outside their range.
 
R

RoSsIaCrIiLoIA

-INT_MIN is performed using signed int arithmetic (before the assignment), and it can
overflow (undefined behaviour).

Note that even if you do...

unsigned u = INT_MIN;
u = -u;

what do you say for
unsigned u = -(INT_MIN + 1);

u += 1;
?
Thanks
 
P

Peter Nilsson

RoSsIaCrIiLoIA said:
what do you say for
unsigned u = -(INT_MIN + 1);
u += 1;

Or just: u = 0u - INT_MIN;

This is well defined [although one comp.std.c regular might disagree about
-(INT_MIN+1)] however...

This can still leave you with u == 0 on theoretical twos complement machines
where UINT_MAX == INT_MAX.
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top