0
int x, N;

and N is always positive. Are the following two lines equivalent?

if (x>=0 && x<N)    

if ( (unsigned)x < (unsigned)N )
Dan
  • 51
  • 2
  • 1
    yes. It's a specific case of [this](http://stackoverflow.com/a/17095534/995714) – phuclv Nov 05 '16 at 11:55
  • 1
    I want to know why the question got down voted – Richardson Ansong Nov 05 '16 at 13:06
  • If you think that any answer has solved your problem, please consider accepting it (the green checkmark to the left of the answer). This will indicate to the community that the question has been answered and will give some reputation to you and the answerer. – 2501 Nov 16 '16 at 10:43

2 Answers2

2

On typical implementations, yes, they are equivalent: if x is negative, (unsigned) x will be greater than INT_MAX. This in turn necessarily means (unsigned) x < (unsigned) N will be false.

On rare implementations, no, they are not equivalent. Implementations are allowed to give int and unsigned int the same amount of value bits (INT_MAX == UINT_MAX), in which case (unsigned) x will not be greater than INT_MAX, and (unsigned) x < (unsigned) N might still be true.

1

The lines are not equivalent when UINT_MAX equals INT_MAX. C permits such implementation.

In that case the wrap-around, when x is converted from int to an unsigned int, may not produce a value that is larger than N.

For example: the value of N is INT_MAX, the value of x is -2. After the conversions from signed int to unsigned int are done, the value of N is INT_MAX, but the value of x is INT_MAX-1. Thus the second if statement is taken, but not the first.

In practice you probably won't encounter such implementations. When the value of UINT_MAX is larger than INT_MAX, the if statements have identical behavior. You can always assert this behavior:

static_assert( UINT_MAX > INT_MAX , "" );
2501
  • 25,460
  • 4
  • 47
  • 87
  • There is also no existing (past or present) implementation that has `UINT_MAX == INT_MAX`. I suppose it's a theoretical future possibility, but wouldn't bet good money on that happening. – Peter Nov 05 '16 at 12:15
  • 1
    @Peter There have been some extremely strange implementations out there, on which little to no information can be found online nowadays. Some things that I would've swore never would've existed did turn out to exist, but there's not really any way of checking. Do you have an authoritative source confirming your claim that no such implementation ever existed? –  Nov 05 '16 at 12:47