Signed and unsigned variable

if a variable is unsigned int
can i assign negative integer to it?

i did so
and when i printed it my computer it printed garbage value
but there was a question in the quiz
there
unsigned int variables were assigned negative values and they were even printed as it is
plz clear my doubt sir!

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.

yes sir i understood that we can’t assign negative value to a unsigned int
if we do so then it is converted first before it is assigned

but sir this question was on quiz on programming of fundamentals.In this there is long long unsigned int which is assigned a negative value
how come it is printed as it is?

ques—
"/* Output ? */
#include
using namespace std;

int main(){
long signed CodingBlocks = 2017;
short unsigned BOSS1 = -2018;
unsigned BOSS2 = -2019;
int BOSS3 = -2020;
long long unsigned BOSS4 = -2021;
short unsigned Nagarro = 2018.9;
long signed HackerBlocks = ‘A’;
cout<<CodingBlocks<<endl;
cout<<BOSS1<<endl<<BOSS2<<endl<<BOSS3<<endl<<BOSS4<<endl;
cout<<Nagarro<<endl;
cout<<HackerBlocks<<endl;

return 0;
}"

ans–
2017 2^16 - 2018 2^32 -2019 -2020 2^64 - 2021 2018 65

sir please clear my doubt??

I apologize for replying this late.
So, now coming back to your doubt.

Let’s say you assign -2 to an unsigned integer
then for 32 bits int it will results in 2^32 - 2
And it would be 2^16 - 2 for short unsigned integer
And similarly, for long long unsigned integer it would be 2^64 - 2

Hope, this would help