c union get type from it -
is possible variable type inside union? example have union:
typedef struct { union { int p; double d; } pointer; int a; struct *next; } mystruct; and have function:
mystruct *getmininlist(mystruct *root) { // things smallest value in list, // simple , don't write here because it's not point return smallest; } sometimes in union integer or double. possible information used? or have write 2 functions: 1 min element in list integer , second min element in list - double?
the union not intrinsically store information such member last written. unless context makes obvious, should have member in struct specifies member of union used. may purpose of a in example, member named type defined explicit enum make semantics more obvious (this type of enum called tagged enum). function needs check each node member use minimum computation.
with type member, code like:
typedef struct { union { int p; double d; } pointer; enum { pointer_int = 0, pointer_double } type; int a; struct *next; } mystruct; static double get_value(const mystruct *x) { return x->type == pointer_double ? x->pointer.d : (double)x->pointer.p; } mystruct *getmininlist(mystruct *root) { mystruct *smallest = root; while (root) { if (get_value(root) < get_value(smallest)) { smallest = root; } root = root->next; } return smallest; } if a has different purpose, add type member above semantics.
note: quick , dirty solution makes assumption values of type int can accurately represented in type double. not case if both int , double 64 bits. in case, quite cumbersome compare large integers , doubles close them because conversion int double truncates low order bits. such truncation can detected testing if (int)(double)root->pointer.p == root->pointer.p. here more elaborate solution case, adapted longer integer type:
static double get_value(const mystruct *x, int *adjust) { if (x->type == pointer_double) { *adjust = 0; return x->pointer.d; } else { double d = (double)s->pointer.p; *adjust = x->pointer.p - (int)d; return d; } } mystruct *getmininlist(mystruct *root) { mystruct *smallest = root; while (root) { int adjust1, adjust2; double val1 = get_value(root, &adjust1); double val2 = get_value(smallest, &adjust2); if (val1 < val2 || (val1 == val2 && adjust1 < adjust2)) { smallest = root; } root = root->next; } return smallest; }
Comments
Post a Comment