When you assign a negative value to an unsigned into variable like:
unsigned int x = -1;
-1 is of type int(signed). The initializer converts this value from int to unsigned int.
During signed-to-unsigned conversion the value is reduced to modulo UINT_MAX + 1, so -1 will convert to UINT_MAX (which is probably 0xffffffff(this is the hexadecimal representation) or 4294967295 if unsigned int is 32 bits).
So, what you were getting was not a garbage value.
You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it’s assigned, and the result will always be >= 0.
The “%d” format is used for (signed) int values. If you use it with an unsigned value or variable, it could print something other than the actual value. Use “%u” to see the actual value, or %x to see it in hexadecimal.
Hope, it will help you in understanding the concept. If you still have any doubts, feel free to ask.