You can use a cast to convert the value. Casting is a language feature that allows you to inform the compiler that you're aware of the consequences of your actions and that it shouldn't warn you about them.
In C casts are of the form ( type )
, where type
is the destination type, so in your example you would do this:
float f = 10.0f;
size_t s = ( size_t )f;
In C++ casting is more specific to the type of casting you want to do. static_cast
, dynamic_cast
, const_cast
, and reinterpret_cast
exist. When converting a numerical value, you would use static_cast
as follows:
float f = 10.0f;
size_t s = static_cast< size_t >( f );
C++ casting is a lot safer than C-style casting (which still exists in C++ for backwards compatibility), so if you're writing C++ code, you should always use the C++ cast operators.
In addition to the above, when casting from a floating point value to an integer value you should consider any rounding that may occur. (Which is what the compiler is warning you about: You can - and probably will - lose numerical accuracy by converting a float to a size_t.) For these types of conversion (implicit or cast), the rounding is always toward zero, so if you want to round to the closest integer value, you will have to subtract 0.5f from your float if it is negative, and add 0.5f if it is positive. So in C++ your final code would look something like this:
if( f < 0.0f )
{
s = static_cast< size_t >( f - 0.5f );
}
else
{
s = static_cast< size_t >( f + 0.5f );
}
Following the conversation below, you can also call std::lround
from the C++11 standard library to perform the conversion and take care of any rounding issues you might have otherwise encountered. It should be noted, however, that lround
returns a long
which might still cause a truncation warning when assigning to a size_t
.