Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size_t to unsigned int (from API function)

Tags:

c++

size-t

I am using the Oracle API to access a database and this API has a function readBuffer(char * buffer, unsigned int size); to which I cannot make any changes.

I have a class that uses this API and the signature of my function currently takes a std::string and an unsigned int for the size, the problem is that when I pass std::string.size() to the size argument of my function, I get a warning from my compiler that converting from size_t to unsigned int could cause data loss.

I wondered if there is a valid way to convert the size_t to an unsigned int so I can pass it to my API and not get a warning from the compiler?

I understand the purpose of size_t and searching google for this conversion turns up a lot of results that say "change the function to take a size_t arg" but I CANNOT change the signature of my API in this case.

Any suggestions?

like image 627
Tony The Lion Avatar asked Apr 19 '11 10:04

Tony The Lion


People also ask

Is size_t the same as unsigned int?

On a typical 64-bit system, the size_t will be 64-bit, but unsigned int will be 32 bit. So we cannot use them interchangeably. One standard recommendation is that the size_t be at most as big as an unsigned long.

Can size_t be used as integer?

gcc actually defines size_t as a signed integer type. This means that using size_t rather than an explicit integer type actually *creates* portability annoyance when code is used both with gcc and with a compiler that defines size_t as an unsigned integer type.

Is size_t unsigned or signed?

size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model. The bit width of size_t is not less than 16.

Is size_t guaranteed to be unsigned?

Yes, size_t is guaranteed to be an unsigned type.


2 Answers

Yes, write a helper function that will check whether such conversion is valid and throw an exception otherwise. Something like:

unsigned int convert( size_t what )
{
    if( what > UINT_MAX ) {
       throw SomeReasonableException();
    }
    return static_cast<unsigned int>( what );
}
like image 140
sharptooth Avatar answered Sep 23 '22 21:09

sharptooth


Well, do a static_cast<unsigned int>(mystring.size()).

The reason is that std::size_t is usually pointer-size, but there are 64 bit platforms on which an int is still 32 bits. In this case, the only reason for data loss would be if the string in question had a length of more than 2^32 bytes.

If you know that this won't happen, put an assert somewhere to catch this case and static_cast the compiler to silence.

like image 23
Alexander Gessler Avatar answered Sep 23 '22 21:09

Alexander Gessler