Re: how to cast from (void*) to other types?




Roman Mashak wrote:
> Hello, David!
> You wrote on 19 Dec 2005 06:49:20 -0800:
>
> DR> "It's supposed to keep parameter name and it's value, which can be
> DR> different
> DR> type (string or unsigned int)"
>
> DR> While it might be useful to keep multiple types, he didn't ask for it.
> DR> Mind you, I prefer your other suggestion, keep everything as strings
> DR> then use accessors (config_get_string, config_get_double,
> DR> config_get_int,
> DR> config_get_bool, etc) to decied what to convert the string to. Neater.
> The method proposed by RH earlier works fine for me. What about using
> unions, can you give example to let me understand clearly?
>
> With best regards, Roman Mashak. E-mail: mrv@xxxxxxxx

Instead of doing this:

typedef struct config_s {
char parameter[BUFLEN];
int valuetype; /* 0 = str, 1 = unsigned int, 2 = double, 3=?... */
char strvalue[MAXLEN];
unsigned int uivalue;
double dvalue;

} config_t;

You could do this:

typedef struct config_s {
char parameter[BUFLEN];
int valuetype; /* 0 = str, 1 = unsigned int, 2 = double, 3=?... */
union {
char strvalue[MAXLEN];
unsigned int uivalue;
double dvalue;
} value;
} config_t;

Having it be a union has a few virtues

1) saves memory, which usually isn't a big deal, but could be if you
have a union of lots of types

2) clarifies intent. These values are mutually exclusive. You should
have
exactly one of them.

That said, I think it makes rather more sense to have a config
mechanism
where everything is strings and the accessor determines what the type
is...

-David

.



Relevant Pages

  • Re: Application of Union in C
    ... is to use a `union` with a `char` array: ... Reading out values of `b` is always OK, as `char` cannot have ... It's much better to use unsigned char rather than char (which can be ... storing a value in one member of a union and then reading ...
    (comp.lang.c)
  • Re: Unions, storage, ABIs
    ... > char Char; ... first address of the union. ... member. ... Even when compiled with a different compiler you could ...
    (comp.lang.c)
  • Re: Application of Union in C
    ... int main ... union test t; ... in our example it is x..(int -4by and char -1by) ...
    (comp.lang.c)
  • Re: Alignment
    ... union aligned_append_u { ... char whatever; ... unsigned int* t_uint; ... float* t_ufloat; ...
    (comp.lang.c)
  • Re: How to escape the Ocamls superfluous parentheses and type declarations?
    ... > This expression has type char but is here used with type int ... why can't it infer the union of the types ... its a constructor. ...
    (comp.lang.ml)