-x == ~x + 1

C

Craig

Will -x == ~x + 1 always be true if x is an unsigned integer type?
This certainly won't always hold if x is signed. The reason I come to
this conclusion is that unsigned numbers must wrap, and there is no
special logic for handling negative numbers. This would then cause
unsigned numbers to behave as 2-s complement numbers, and thus
guarantee -x == ~x + 1.
 
P

Peter Nilsson

Craig said:
Will -x == ~x + 1 always be true if x is an unsigned integer type?

For unsigned types not subject to integral promotion to int, yes.
This certainly won't always hold if x is signed.

The expression potentially invokes undefined behaviour for signed types.
 
C

Clark Cox

Will -x == ~x + 1 always be true if x is an unsigned integer type?

Yes, as long as that unsigned interger type will not be promoted to
int. For example, if the type is "unsigned char" or "unsigned short" (or
"char" if "char" is an unsigned type on your platform), then the result
is undefined.

But, if the type is "unsigned int", "unsigned long" or "unsigned long
long", then the result will be true.
This certainly won't always hold if x is signed.

Correct.
 
K

Kevin Goodsell

Clark said:
Yes, as long as that unsigned interger type will not be promoted to
int. For example, if the type is "unsigned char" or "unsigned short" (or
"char" if "char" is an unsigned type on your platform), then the result
is undefined.

What if the type is unsigned char, unsigned short, or char (being
unsigned on this theoretical platform), but the type does not promote to
int?

-Kevin
 
C

Clark Cox

Kevin Goodsell said:
What if the type is unsigned char, unsigned short, or char (being
unsigned on this theoretical platform), but the type does not promote to
int?

-Kevin

Well, as per my first sentence ...
int.

...it will not be undefined. (Though, looking my post now, I admit I
could have been a little clearer).
 
D

Dan Pop

In said:
What if the type is unsigned char, unsigned short, or char (being
unsigned on this theoretical platform), but the type does not promote to
int?

Then, it promotes to unsigned int and there are no problems. The
previous poster was quite clear that only the promotion to int breaks it.

OTOH, (with the exception of unsigned short getting "promoted" to unsigned
int) your scenario is not going to happen on a hosted implementation.

Dan
 

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

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top