C:将 int 转换为 size_t
在 32 位和 64 位 Linux 平台上,在 C99 中将 int
转换/转换为 size_t
的正确方法是什么?
例子:
int hash(void * key) {
//...
}
int main (int argc, char * argv[]) {
size_t size = 10;
void * items[size];
//...
void * key = ...;
// Is this the right way to convert the returned int from the hash function
// to a size_t?
size_t key_index = (size_t)hash(key) % size;
void * item = items[key_index];
}
What is the proper way to convert/cast an int
to a size_t
in C99 on both 32bit and 64bit linux platforms?
Example:
int hash(void * key) {
//...
}
int main (int argc, char * argv[]) {
size_t size = 10;
void * items[size];
//...
void * key = ...;
// Is this the right way to convert the returned int from the hash function
// to a size_t?
size_t key_index = (size_t)hash(key) % size;
void * item = items[key_index];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有算术类型在 C 中都会隐式转换。很少需要强制转换 - 通常仅当您想要向下转换、减少模 1 加上较小类型的最大值时,或者当您需要强制算术进入无符号模式才能使用时无符号算术的性质。
就我个人而言,我不喜欢看到强制转换,因为:
当然,如果您启用一些非常挑剔的警告级别,您的隐式转换可能会导致大量警告,即使它们是正确的......
All arithmetic types convert implicitly in C. It's very rare that you need a cast - usually only when you want to convert down, reducing modulo 1 plus the max value of the smaller type, or when you need to force arithmetic into unsigned mode to use the properties of unsigned arithmetic.
Personally, I dislike seeing casts because:
Of course if you enable some ultra-picky warning levels, your implicit conversions might cause lots of warnings even when they're correct...
很好。实际上你甚至不需要演员表:
做同样的事情。
is fine. You actually don't even need the cast:
does the same thing.
除了转换问题(您不需要像前面所述的那样)之外,代码中还可能存在一些更复杂的问题。
如果
hash()
应该返回数组的索引,它也应该返回size_t
。由于事实并非如此,当key_index
大于INT_MAX
时,您可能会得到奇怪的效果。我想说
size
、hash()
、key_index
应该都是相同的类型,可能是size_t
到确保,例如:Aside from the casting issue (which you don't need as stated before), there is some more intricate things that might go wrong with the code.
if
hash()
is supposed to return an index to an array, it should return asize_t
as well. Since it doesn't, you might get weird effects whenkey_index
is larger thanINT_MAX
.I would say that
size
,hash()
,key_index
should all be of the same type, probablysize_t
to be sure, for example: