【问题标题】:converting from size_t to unsigned int从 size_t 转换为 unsigned int
【发布时间】:2011-11-05 10:00:06
【问题描述】:
从 size_t 转换为 unsigned int 是否可能导致溢出。
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 ?
语言:c++
平台:任意
【问题讨论】:
标签:
c++
type-conversion
unsigned-integer
【解决方案1】:
是的,size_t 和 int 的大小不一定相同。 64 位 size_ts 和 32 位 ints 实际上很常见。
C++11 草案 N3290 在 §18.2/6 中说明了这一点:
size_t 类型是实现定义的无符号整数类型,它大到足以包含任何对象的大小(以字节为单位)。
另一方面,unsigned int 只需要能够存储从 0 到 UINT_MAX 的值(在 <climits> 中定义并遵循 C 标准头 <limits.h>),仅保证至少为 65535 (216-1).
【解决方案2】:
是的,在某些平台上可能会发生溢出。比如size_t可以定义为unsigned long,很容易大于unsigned int。