Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does the incrementation of unsigned int cause undefined behavior when the variable reach the Max

Tags:

c++

c

int

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

}
like image 682
Anis_Stack Avatar asked Dec 13 '13 15:12

Anis_Stack


People also ask

What happens when an unsigned integer variable overflows?

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.

Is signed integer overflow undefined?

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.

What happens when you cast an int to an unsigned int?

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.)


1 Answers

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."

like image 57
ouah Avatar answered Sep 23 '22 12:09

ouah