Search code examples
c++type-conversionunsigned-integer

converting from size_t to unsigned int


Is it possible that converting from size_t to unsigned int result in overflow .

 size_t x  = foo ( ) ;  // foo ( ) returns a value in type size_t
 unsigned int ux = (unsigned int ) x ;

 ux == x  // Is result of that line always 1 ?

language : c++

platform : any


Solution

  • Yes it's possible, size_t and int don't necessarily have the same size. It's actually very common to have 64bit size_ts and 32bit ints.

    C++11 draft N3290 says this in §18.2/6:

    The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.

    unsigned int on the other hand is only required to be able to store values from 0 to UINT_MAX (defined in <climits> and following the C standard header <limits.h>) which is only guaranteed to be at least 65535 (216-1).