C 中的安全铸造
大家好,我有这段代码:
void writer(void* param){
if(NULL == param){
return;
}
param = (param_t*)param;
...
}
它是否安全,参数来自 param_t* 类型,但是当我在函数中使用它时,每次进行转换时我都感到恶心,有人有另一个优雅的解决方案吗?提前致谢
hello everyone I have this snippet of the code:
void writer(void* param){
if(NULL == param){
return;
}
param = (param_t*)param;
...
}
is it safe code, or not, param is from type param_t*, but I'm sick doing every time casting when I use it in function, do Somebody have another elegant solution? thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个奇怪的禁止操作。
当您定义函数时,您说参数的类型为
void*
。然后,通过强制转换,将其显式转换为
param_t*
编译器通过赋值隐式地将
param_t*
转换为void*
。你需要另一个变量
That is a strange no-op.
When you define the function you say param is of type
void*
.Then, with the cast, you explicitly convert it to
param_t*
And the compiler implicitly converts that
param_t*
tovoid*
with the assignment.You need another variable
即使指针值为 NULL,赋值中的(隐式)强制转换也是安全的,因此无需推迟它。你可以这样做:
The (implicit) cast in the assignment is safe even if the pointer value is NULL, so there's no need to defer it. You could do this:
您不必将 void* 转换为 C 中的另一种指针类型。
所以只需执行以下操作:(
但是为什么您要使用 void* 作为参数呢?)
You do not have to cast a void* to another pointer type in C.
So just do:
(But why are you using a void* for the argument anyway?)
显而易见的解决方案是避免使用
void *
并使用param_t *
代替,如下所示:如果您知道,您可以删除 NULL 测试从未使用 NULL 指针调用。或者,您可以将其替换为
assert(param != NULL)
。The obvious solution is to avoid using
void *
and useparam_t *
instead, as in:You could drop the NULL test if you know that it's never called with a NULL pointer. Alternatively, you could replace it with
assert(param != NULL)
.