Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINT_MAX + 1 equals what?

What is the defined behavior in C for UINT_MAX + 1u? How safe is to assume it is zero?

like image 998
lvella Avatar asked Feb 15 '13 16:02

lvella


People also ask

What is UINT_ MAX?

UINT_MAX is the maximum value for an object of type unsigned int.

What is the range of signed integer?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647].


2 Answers

From the standard (C11, 6.2.5/9, emphasis mine):

[...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

If UINT_MAX is 10:

(10 + 1) % (10 + 1) == 0

So, yes, it's safe to assume it's zero.

like image 151
netcoder Avatar answered Sep 22 '22 13:09

netcoder


It's worth emphasizing that while unsigned behavior is well-defined, signed integer overflow isn't:

  • http://en.wikipedia.org/wiki/Integer_overflow

In the C programming language, signed integer overflow causes undefined behavior, while unsigned integer overflow causes the number to be reduced modulo a power of two

A very good paper on the subject:

  • http://www.cs.utah.edu/~regehr/papers/overflow12.pdf

EXAMPLES OF C/C++ INTEGER OPERATIONS AND THEIR RESULTS

Expression             Result
----------             ------
UINT_MAX+1             0
LONG_MAX+1             undefined
INT_MAX+1              undefined
SHRT_MAX+1             SHRT_MAX+1 if INT_MAX>SHRT_MAX, otherwise undefined
char c = CHAR_MAX; c++ varies
-INT_MIN               undefined
(char)INT_MAX          commonly -1
1<<-1                  undefined
1<<0                   1
1<<31                  commonly INT_MIN in ANSI C and C++98; undefined in C99 and C++11
1<<32                  undefined
1/0                    undefined
INT_MIN%-1             undefined in C11, otherwise undefined in practice
like image 43
paulsm4 Avatar answered Sep 25 '22 13:09

paulsm4