views:

346

answers:

3

I have read in many places that integer overflow is well-defined in C unlike the signed counterpart.

Is underflow the same?

For example:

unsigned int x = -1; // Does x == UINT_MAX?

Thanks.

I can't recall where, but i read somewhere that arithmetic on unsigned integral types is modular, so if that were the case then -1 == UINT_MAX mod (UINT_MAX+1).

+4  A: 

-1, when expressed as a 2's complement number, amounts to 0xFF...F for how ever many bits your number is. In an unsigned number space that value is the maximum value possible (i.e. all the bits are set). Therefore yes, x == UINT_MAX. The following code emits "1" on a C99 strict compiler:

#include <stdio.h>
#include <stdint.h>
#include <limits.h>

int main(int argc, char **argv){
  uint32_t x = -1;      
  printf("%d", x == UINT_MAX ? 1 : 0);
  return 0;
}
vicatcu
Are twos-complement numbers required by the standard?
BlueRaja - Danny Pflughoeft
No, 2s complement is not required by the standard, so this solution is not general; see my answer.
Doug Currie
It is not required that the maximum value of `uint32_t` be `UINT_MAX` - `UINT_MAX` can be as small as 65535 and as large as `ULONG_MAX`. If you change that `uint32_t` to `unsigned` it will be correct.
caf
+1  A: 

You are mixing signed and unsigned numbers, which is uncool.

unsigned int x = 0u - 1u; // is OK though
Doug Currie
It may or may not be uncool, but it is perfectly well defined standard-conformant C.
Stephen Canon
@Stephen Canon, Untrue. The bitwise representation of -1 is not defined. It could be ones complement, for example.
Doug Currie
@Stepen, "standard-conformant" maybe, but "well defined"? That's the crux of the question.
Mark Ransom
The bitwise representation of -1 (or any signed integer) doesn't figure into it. §6.3.1.3 specifies the behavior.
Stephen Canon
Thanks, Stephen, you are right. Lint likes my solution better, though. ;-)
Doug Currie
+7  A: 
Stephen Canon
Your reference is fine, but not applicable since the expression -1 involves signed operands, not unsigned operands.
Doug Currie
The question already admits that overflow is well defined. The question is about negative numbers, not positive.
Mark Ransom
@Doug, @Mark: The question is about conversions from signed to unsigned integers, which is specified by §6.3.1.3.
Stephen Canon
+1 for correct answer, §6.3.1.3 appears to be a very contorted way of requiring `(unsigned int)(-1) == UINT_MAX` without necessarily requiring signed numbers to use two's complement.
BlueRaja - Danny Pflughoeft
@Stephen, thanks for being persistent (and for digging up 6.3.1.3); I stand corrected. Too bad about accepted answer http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe "the internal representation of the number does not change"
Doug Currie
holy esoteric reference Batman!
vicatcu