What is meant by an unsigned int?

Jan 20, 2012 at 5:59pm
When they say the vector class member function size() returns an unsigned int, what exactly does that mean? I understand an insigned int is a non-negative integer, but isn't that the same as saying an unsigned int is a positive integer? According to the book i'm reading the following loop is incorrect. for (int i= 0; i < sample.size( ); i++) Apparently you need to declare the variable i as an unsigned int. My question is, if you have already intialized i as a positive integer, why should the compiler have a problem comparing the value of i to the value returned by sampe.size()?
Last edited on Jan 20, 2012 at 6:01pm
Jan 20, 2012 at 6:10pm
A regular int uses 31 bits representing a number and 1 bit representing the negative sign. This has a range of -2,147,483,647 to +2,147,483,647.

An unsigned int uses that sign bit as data instead of representing a sign. This means that it uses 32 data bits which gives you larger maximum but you can't use a negative (0 to 4,294,967,295).

This is more interesting when we are looking at chars which are only 1 byte (8 bits long). A char has a range -127 to 127 while an unsigned char has a range of 0 to 255.
Last edited on Jan 20, 2012 at 6:12pm
Jan 20, 2012 at 6:20pm
> I understand an insigned int is a non-negative integer,
> but isn't that the same as saying an unsigned int is a positive integer?

Not precisely. Zero is neither positive nor negative; it is both non-positive and non-negative.

> According to the book i'm reading the following loop is incorrect.
> for (int i= 0; i < sample.size( ); i++)

In practise, the int will be converted to an unsigned integral type before the comparison is made. It would work as expected if the size of the vector is not greater than
std::numeric_limits<int>::max()


> Apparently you need to declare the variable i as an unsigned int.

That would work as expected if the size of the vector is not greater than
std::numeric_limits<unsigned int>::max()


To be pedantically correct,
1
2
3
4
void foo( const std::vector<std::string>& sample )
{
    for( std::vector<std::string>::size_type i = 0 ; i < sample.size() ; ++i ) { /* ... */ }
}


In practise, a std::size_t would do quite nicely if the standard allocator is used.
Last edited on Jan 20, 2012 at 6:21pm
Jan 20, 2012 at 6:53pm
To both of you Stewbond and JLBorges, thank you very much. Your answers were very helpful. I'M MARKING THIS ONE AS SOLVED!!
Jan 20, 2012 at 8:04pm
be aware that you can pass a non-positive value to unsigned int and compiler will mostly give an warning only but no error.

result will be MAX value - assigned value, not what you wanted!
Topic archived. No new replies allowed.