user1833028
user1833028

Reputation: 943

C++ why does this not provide the system maximum size for integer?

So, if I understand correctly, an integer is a collection of bytes, it represents numbers in base-two format, if you will.

Therefore, if I have unsigned int test=0, is should really just consist of a field of bits, all of which are zero. However,

unsigned int test=0;
test=~test;

produces -1.

I would've thought that this would've filled all the bits with '1', making the integer as large as it can be on that system....

Thanks for any help!

Upvotes: 0

Views: 143

Answers (3)

banarun
banarun

Reputation: 2321

Alternatively you can use:

unsigned int test =0;
test--;

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477348

You're not understanding correctly. An integer represents an integer, and that's it. The specifics of the representation are not part of the standard (with a few exceptions), and you have no business assuming any correlation between bitwise operations and integer values.

(Ironically, what the standard does mandate via modular arithmetic rules is that -1 converted to an unsigned integer is in fact the largest possible value for that unsigned type.)

Update: To clarify, I'm speaking generally for all integral types. If you only use unsigned types (which I assumed you weren't because of your negative answer), you have a well-defined correspondence between bitwise operations and the represented value.

Upvotes: 4

unwind
unwind

Reputation: 399949

How do you print the value?

If it's displayed as "-1" or a large unsigned integer is just a manner of the bits are interpreted when printing them out, the bits themselves don't know the difference.

You need to print it as an unsigned value.

Also, as pointed out by other answers, you're assming a lot about how the system stores the numbers; there's no guarantee that there's a specific correlation between a number and the bits used to represent that number.

Anyway, the proper way to get this value is to #include <climits> and then just use UINT_MAX.

Upvotes: 12

Related Questions