I want to set the value of the (dereferenced) passed variable to NULL
if it is a const char *
and to 0
if it is a double
, assuming that NULL
is defined as (void *)0
and sizeof(const char *) == sizeof(double)
, is this code safe? is there a better approach to achieve the same?
If not, please, don't suggest to use union
s, I am stuck with void *
(building an interpreter) and I can not pass the type as parameter, I only need those 2 type (const char *
and 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;
}