use*_*450 12 c int casting c99 size-t
在32位和64位Linux平台上转换/转换int为size_tC99 的正确方法是什么?
例:
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];
}
Run Code Online (Sandbox Code Playgroud)
R..*_*R.. 15
所有算术类型都在C中隐式转换.很少需要转换 - 通常只有当你想要转换时,减少模1加上较小类型的最大值,或者你需要强制算术进入无符号模式才能使用无符号算术的属性.
就个人而言,我不喜欢看演员,因为:
当然,如果你启用一些超级挑剔的警告级别,你的隐式转换可能会导致很多警告,即使它们是正确的......
size_t key_index = (size_t)hash(key) % size;
Run Code Online (Sandbox Code Playgroud)
很好.你实际上甚至不需要演员:
size_t key_index = hash(key) % size;
Run Code Online (Sandbox Code Playgroud)
做同样的事情.