简体   繁体   中英

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

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

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

Unsigned arithmetic is defined to be modular, with a modulo of 2^BITS == MAX+1 . So incrementing the maximum value is defined to give zero.

Signed overflow, on the other hand, does give undefined behaviour.

This is the case in both C and C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM