C
Clint Olsen
I was wondering if it's considered undefined behavior to use a member of a
union when it wasn't initialized with that member. Example:
typedef unsigned long hval_t;
hval_t hval_init(void)
{
union hval_init_u { double dbl; hval_t hval; };
union hval_init_u phi = { (sqrt(5) + 1) / 2 }; /* golden ratio */
return phi.hval;
}
I saw on a thread here quite some time ago that it's reasonable to use a
char * to index into a double value and copy the bytes to an unsigned long,
but it seems much quicker and easier to do it this way.
I was wanting to use this as my default bit pattern for a hash function.
It doesn't have to be portable. It just needs to be somewhat random, and
this seemed like a reasonable way.
-Clint
union when it wasn't initialized with that member. Example:
typedef unsigned long hval_t;
hval_t hval_init(void)
{
union hval_init_u { double dbl; hval_t hval; };
union hval_init_u phi = { (sqrt(5) + 1) / 2 }; /* golden ratio */
return phi.hval;
}
I saw on a thread here quite some time ago that it's reasonable to use a
char * to index into a double value and copy the bytes to an unsigned long,
but it seems much quicker and easier to do it this way.
I was wanting to use this as my default bit pattern for a hash function.
It doesn't have to be portable. It just needs to be somewhat random, and
this seemed like a reasonable way.
-Clint