我想设置(取消引用)传递变量的值,NULL如果它是a const char *,0如果它是a double,假设NULL被定义为(void *)0和sizeof(const char *) == sizeof(double),这个代码是否安全?是否有更好的方法来实现同样的目标?
如果没有,请不要建议使用unions,我坚持void *(构建一个解释器)我不能传递类型作为参数,我只需要那两种类型(const char *和double).
#include <stdio.h>
#include <string.h>
static void set0(void *param)
{
if (sizeof(const char *) == sizeof(double)) {
*(const char **)param = 0;
}
}
int main(void)
{
const char *str = "Hello";
double num = 3.14;
printf("%s\n", str);
printf("%f\n", num);
set0(&str);
if (str != NULL) {
printf("%s\n", str);
}
set0(&num);
printf("%f\n", num);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为了使其即使在sizeof(double)与sizeof(const char*)其他条件必须相同的平台上也是安全的:系统表示double的方式必须将NULL指针的位解释为0.0.
虽然这是在许多平台上真实的,因为这两个NULL和0.0被表示为的零个字节相同长度的序列,决不是标准要求这是真实的.零双可能具有与IEEE-754中的表示不同的表示.类似地,NULL指针不需要表示为零(尽管编译器必须确保NULL指针的零比较成功).因此,您最终得到了相当不可移植的代码.