Dan
Dan

Reputation: 51

Are these two expressions equivalent

int x, N;

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

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

if ( (unsigned)x < (unsigned)N )

Upvotes: 0

Views: 101

Answers (2)

2501
2501

Reputation: 25752

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 , "" );

Upvotes: 1

user743382
user743382

Reputation:

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.

Upvotes: 2

Related Questions