Frage

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

War es hilfreich?

Lösung

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).

Andere Tipps

Yes, overflow can occur on some platforms. For example, size_t can be defined as unsigned long, which can easily be bigger than unsigned int.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top