sizeof(size_t)可以小于sizeof(int)吗? [英] Can sizeof(size_t) be less than sizeof(int)?

查看:96
本文介绍了sizeof(size_t)可以小于sizeof(int)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sizeof(size_t)是否可以小于 sizeof(int)?

C和/或C ++标准是否保证使用 unsigned int 进行数组索引总是安全的?

Do the C and/or C++ standards guarantee that using unsigned int for array indexing is always safe?

推荐答案

是的, sizeof(size_t)原则上可以小于 sizeof(int).我不知道有什么实现是正确的,而且很可能没有实现.我可以想象使用64位 int 和32位 size_t 的实现.

Yes, sizeof(size_t) can, in principle, be less than sizeof(int). I don't know of any implementations where this is true, and it's likely that there are none. I can imagine an implementation with 64-bit int and 32-bit size_t.

但是使用 unsigned int 为数组建立索引是安全的-只要索引的值在数组长度所施加的范围内即可.仅要求 [] 运算符的参数为整数.它不会转换为 size_t .它是根据指针算术定义的,其中 + 运算符具有一个作为指针的参数,以及另一个任何整数类型的参数.

But indexing an array with unsigned int is safe -- as long as the value of the index is within the bounds imposed by the length of the array. The argument to the [] operator is merely required to be an integer. It's not converted to size_t. It's defined in terms of pointer arithmetic, in which the + operator has one argument that's a pointer and another argument that is of any integer type.

如果 unsigned int 宽于 size_t ,则超出 SIZE_MAX unsigned int 索引值将几乎当然会引起问题,因为数组不是那么大.在C ++ 14和更高版本中,明确禁止定义大于 SIZE_MAX 个字节的类型(3.9.2 [compound.types]段落2).在早期版本的C ++和所有版本的C中,都没有明确禁止使用它,但是任何理智的实现都不太可能允许它.

If unsigned int is wider than size_t, then an unsigned int index value that exceeds SIZE_MAX will almost certainly cause problems because the array isn't that big. In C++14 and later, defining a type bigger than SIZE_MAX bytes is explicitly prohibited (3.9.2 [compound.types] paragraph 2). In earlier versions of C++, and in all versions of C, it isn't explicitly prohibited, but it's unlikely that any sane implementation would allow it.

这篇关于sizeof(size_t)可以小于sizeof(int)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆