trouble with unsigned type modifier

Hey all.
I'm having trouble understanding unsigned type modifier.
Consider this code:

1 vector<unsigned int>numbers;
2
3 numbers.push_back(-5);
4
5 cout << numbers[0];
6
7 if (numbers[0] != -5)
8 cout << "works ";

Line 3: Because vector type is unsigned int, push_back will not store -5 into vector, but will store some number that is currently in position of -5.
Line number 5 confirms that.

Line 7: But why does if condition fail? It checks whether -5 is at position 0. It isn't. If i change if condition to == . It prints out the string.
My guess is that -5 is converted to an unsigned int on line 7(or numbers[0] to an int), but thats just a wild guess
you could also just cout << numbers[0] to see what it is
Last edited on
Skillless is basically correct. It isn't technically "converted", but it is close enough to be correct.

Anyway, if you want to get into detail...assuming 32 bit int here.

Binary representation of -5:
1111111111111111111111111111111111111111111111111111111111111011


Binary representation of 18446744073709551611:
1111111111111111111111111111111111111111111111111111111111111011


Note that they are exactly the same. unsigned merely tells the compiler to interpret the number as the bottom type, where if it is signed, it treats it like the type.
ok tnx.

Generaly speaking.
For what are type modifiers used for, if you can't use them for ckecking for correct value?

And another thing Skillless:

I thought -5 is converted to unsigned int when push_back is called. That is because if i try to put string into unsigned int there is an compilation error. So some form of type checking does exist.
I really don't know.

Last edited on
hey all

I found this in The c++ prgramming language book :

"The reason for providing more than one integer type, more than one unsigned type, and more than one floatingpoint type is to allow the programmer to take advantage of hardware characteristics.
On many machines, there are significant differences in memory requirements, memory access
times, and computation speed between the different varieties of fundamental types. If you know a
machine, it is usually easy to choose, for example, the appropriate integer type for a particular variable.
Writing truly portable lowlevel
code is harder."

Topic archived. No new replies allowed.