1

Let's assume we have the following loop:

    for (int i = 1; i < 2; i--)
    {
        cout << i << endl;
    }

Without a doubt, this is an infinite for-loop. However, my question is that for how long will it run? Because my prof said that given that an int is 4 bytes = 32 bits, it can store a number from -2147483648 to 2147483647. Given this, he went on to say that in a for-loop, if it ever reach one of these numbers, and the loop is still programmed to continue (like this one is), then the number will become positive, and the condition will be met, terminating the loop.

My question is exactly is: how does this happen? Why does the number -2147483648 become +2147483648 in the for-loop, and why does +2147483648 turn to -2147483648 in the for-loop? Because I used to think that a segmentation fault would occur as soon as the counter hit 2147483649. Thanks for your responses!

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31

2 Answers2

5

To answer your title question; Will an Infinite Loop ever end by Itself:

No.

But your loop is not only not infinite, it will not even run once because of the for loop condition.

for (int i = 1; i > 2; i--)

i, at 1 will never satisfy the loop condition i>2.

Lets say though that you meant i < 2, then the answer is, I dont know. Integer overflow is undefined behaviour in C++ (see here).

It will in most cases wrap around, but since the behaviour is undefined, there is no real point to discussing what will really happen.

Community
  • 1
  • 1
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
2

why does +2147483647 turn to -2147483648

This becomes evident if you write your integer in bit representation. For the sake of simplicity lets take an 8 bit variable like char or std::int8_t. An 8 bit type can hold 2^8 = 256 different values. For a signed variable these are the values from -128 to 127 (The 0 is also a value, therefore only up to 127). A few examples:

0000 0000 = 0
0000 0001 = 1
0111 1111 = 127

1111 1111 = -1
1111 1110 = -2
1000 0000 = -128

You can easily see that the value -1 needs to be 1111 1111 if you for example calculate -1 + 2 = 1

  1111 1111
+ 0000 0010
  1111 11     (carry)    
  ---------
  0000 0001

If you increment the value 0111 1111 = 127 you get 1000 0000 = -128. Thats exactly what happened in your case, just with a few more bits.

However as Fantastic Mr Fox already mentioned, whether it really wraps around is dependent on the compiler implementation and not defined by the standard.

Shaana
  • 326
  • 1
  • 5