1

While was solving this problem on hackerrank, I noticed a strange thing in the for loop. First, let me show an example code:

#include <bits/stdc++.h>
using namespace std;
#define modVal 1000000007;

int main() {
    for(long long int i=2;i>=0;--i){
        cout<<"here: "<<i<<endl;
    }
}

input: 123

output: here: 2 here: 1 here: 0 164

Now, when I change long long int to unsigned long long int in for loop for the initialization of variable i. The variable i gets initialized with 18446744073709551615. Why is this happening?

psclkhoury
  • 113
  • 1
  • 8
h s
  • 304
  • 3
  • 14

3 Answers3

6

When the variable is unsigned, i >= 0 is always true. So your loop never ends. When i gets to 0, the next -- makes i 0xFFFFFFFFFFFFFFFF (decimal 18446744073709551615).

Michael Chourdakis
  • 8,819
  • 2
  • 32
  • 61
3

Because unsigned types can't be negative, attempting to set them to a negative value will make them wrap around and instead hold std::numeric_limits<T>::max() - abs(value) + 1 where T is the type and value the value below 0.

In your loop once i reaches 0 the condition i >= 0 is still met and thus it would get decremented to -1 but that is impossible for unsigned types as explained above and thus the loop will never exit.

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
3

The unsigned numbers as the name suggests don't take signed values. So when i = -1 it is actually 0xFFFFFFFFFFFFFFFF(18446744073709551615 in decimal).

You can see that yourself with the modified program.

 #include <bits/stdc++.h>
 using namespace std;
 #define modVal 1000000007;

 int main() {
    for(unsigned long long int i=2;i>=0;--i){
         cout<<"here: "<<i<<endl;
       if(i > 3)
          return 0;
   }
 }
Christina Jacob
  • 640
  • 5
  • 16