I want to understand how the compiler gives me garbage value when I declare an unsigned int and makes it equal to -2.
I know that unsigned int cannot be negative, hence, giving me garbage value. BUT, I want to know how that works. What happens to the memory address when we process this code? Is test1 not saved anywhere in memory? Help me understand it please.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main()
{
unsigned int test1;
test1 = -2;
cout << test1 << endl;
system("PAUSE");
return 0;
}
|
output:
1 2
|
4294967294
Press any key to continue . . .
|
Also, I have another question.
When we want to add two values, let's say that we want to add
unsigned u = 10
and
int i = -42
usually, the compiler will try to convert one type to another. How does it decide from what type to what type to convert?
In other words, in this case, the int will be converted to unsigned, but why not the opposite?
On what basis does the compiler converts types?