I have a counter in my code and I want my counter back to 0 when it reach the unsigned int max value. I tested with a small code and it works but I do not know if it's an undefined behaviour
#include <stdio.h>
#include <string.h>
main()
{
unsigned int a = 0;
a= ~a; // Max value of unsigned int
printf("%u \n", a );
a= a+1; //is it allowed to increment "a" when "a" reach the Max ?
printf("%u \n", a ); // display 0
}
In general, when an unsigned int overflows, it rolls over to zero. So UINT_MAX + 5 rolls over and becomes 4. It would be the difference between the max uint value and the value of what would have been the overflow value.
12.2. 1 Basics of Integer Overflow In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow.
You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
a= a+1; //is it allowed to increment "a" when "a" reach the Max ?
Yes, unsigned integers never overflow (this is C terminology). So UINT_MAX + 1
is defined behavior and is evaluated to 0
.
(C99, 6.2.5p9) "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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With