Search code examples
cfor-loopinteger-overflowunsigned-integertermination

Does the for loop terminate becaue of unsigned int overflow?


I am studying for my C exam and I've been asked this question:

"Given this code, does it terminate? If so, why?"

 int main() {
   unsigned int i;
   for (i=1; i>0; i++);
   return 0;
 }

I've been thinking that it does terminate due to the nature of the unsigned int: in the for loop i goes from 1 to the max value (which I believe is 2^32-1) freely, then the loop encounters an overflow exception and it goes back to 0, the first value for an unsigned int. This is in conflict with the condition i>0 of the loop and it terminates it, going to "return 0" and terminating the program.

Is my hypothesis correct? We have no solution given by the professor so while it does make sense to me it might be horribly incorrect, that's why I need your help.


Solution

  • Basically, you are correct in everything you say. Once the loop counter goes past UINT_MAX (usually 2^32-1), it will wrap to 0, which causes the loop to terminate due to the loop condition no longer being satisfied.

    The only thing wrong with what you say is that you used the word "exception". There is nothing wrong with the result of an unsigned integer arithmetic operation being larger than UINT_MAX. According to C11 Standard - 6.2.5 Types(p9), the result is well-defined. It will just be subjected to modulo UINT_MAX + 1 so that it fits into an unsigned int.

    However, beware that with signed integers, an overflow causes undefined behavior. See the following StackOverflow question for further information:

    Why is unsigned integer overflow defined behavior but signed integer overflow isn't?.