Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of these is the more portable way to set the maximum value of an unsigned integer?

Tags:

c

casting

c99

In C99 compliant C, assuming no preprocessor macro defines, which is the more portable way of setting the maximum value of an unsigned integer:

unsigned x = -1;

or

unsigned y = ~0;

I recall a few years ago I came across a thread which claimed that setting the unsigned int to -1 was more portable due to ~0 having some sort of trap representation on obscure systems; I no longer feel certain that is true though.

I know the behavior of setting a negative value to an unsigned variable is well defined in the C99 standard (i.e. modulo value, etc), but what about the inversion of 0?

Furthermore, if both operations are equally portable, and assuming there is no compiler optimization, which operation would be more efficient in terms of clock cycles?

like image 630
Vilhelm Gray Avatar asked Dec 07 '22 08:12

Vilhelm Gray


1 Answers

unsigned x = UINT_MAX; works (after including <limits.h>), by definition of UINT_MAX.

unsigned x = -1; works by definition of how operations work with unsigned integers (UINT_MAX+1 is added or subtracted to make the result representable, so -1 becomes -1+UINT_MAX+1 which equals UINT_MAX).

unsigned x = ~0; is not guaranteed to work, because ~ is defined as an operation on the bits of an integer, rather than an operation on the numeric value, but the bits of signed integers are not fully specified by the C standard.

unsigned x = ~0u; works, because 0u is an unsigned integer, and its value bits are fully specified by the C standard.

like image 89
Eric Postpischil Avatar answered Dec 08 '22 22:12

Eric Postpischil