Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Unsigned integers

I have the following program written in C++:

The problem with this program is that if the user inputs a negative number, it is NOT caught by the line if(!cin). I thought that unsigned integers can NOT accept negative numbers. Then why if I enter a negative number to size, it is NOT caught by if(!cin) and the program continues execution with no error messages?

I cannot make use of if(size < 0). I want to show how unsigned integers can solve the problem of negative input.

like image 609
Matthew Avatar asked Dec 05 '25 19:12

Matthew


1 Answers

The difference between unsigned and signed integers on most platforms is a sign-bit ... other than that, the actual binary value is the same, it's just interpreted two different ways depending on the sign-ness of the type that the binary value represents. So you can definitely "represent" a negative value input as a unsigned value ... it won't be re-interpreted as that value, but it can definitely be input as that value without an error being set on the stream.

like image 127
Jason Avatar answered Dec 07 '25 08:12

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!