Reputation: 414
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?
Upvotes: 1
Views: 719
Reputation: 11158
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).
Upvotes: 6
Reputation: 685
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;
}
}
Upvotes: 3
Reputation: 36483
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.
Upvotes: 3