We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
It isn't more or less dangerous; it's for readability! You expect a positive value, you use an unsigned (int, short, long ... whatever). By doing so, std:cin can also tell what you're expecting when you query it through cin >> n as the operator>> called depends on the type of n.
Now, about the overflow, an unsigned will never give you an infinite loop if you test it for a null value (what you're doing with while(n)) as the maximal value represented by an unsigned (i.e. all bytes set to 0xFF in memory) will always overflow into 0 and the loop will end (same goes if you decrement 0). As an example:
And you just loop through all representable numbers until you hit 0. This is somehow also true for an int (see the two's complement for more information).
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Maps-STL
You are viewing a single comment's thread. Return to all comments →
It isn't more or less dangerous; it's for readability! You expect a positive value, you use an
unsigned
(int
,short
,long
... whatever). By doing so,std:cin
can also tell what you're expecting when you query it throughcin >> n
as theoperator>>
called depends on the type ofn
.Now, about the overflow, an
unsigned
will never give you an infinite loop if you test it for a null value (what you're doing withwhile(n)
) as the maximal value represented by anunsigned
(i.e. all bytes set to0xFF
in memory) will always overflow into0
and the loop will end (same goes if you decrement0
). As an example:outputs
And you just loop through all representable numbers until you hit
0
. This is somehow also true for anint
(see the two's complement for more information).