C:将int转换为size_t [英] C: cast int to size_t
问题描述
在32位和64位linux平台上,在C99中将 int
转换/转换为 size_t
的正确方法是什么?
What is the proper way to convert/cast an int
to a size_t
in C99 on both 32bit and 64bit linux platforms?
示例:
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];
}
推荐答案
所有算术类型都在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...
这篇关于C:将int转换为size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!