3 ms·
Unions for sure. You can create tagged unions with different data types and shapes (even function code to execute dynamically).
by jbirer 6y ago
Unions for sure. You can create tagged unions with different data types and shapes (even function code to execute dynamically).
- jhallenworld 6y agoUnions are always better than casts. It would be better if casts in C looked like union deselection, because parenthesis are ugly. There really should be an infix casting operator. An example of where this matter is an AST forest, like this: struct node { int tag; }; // Generic node struct infixnode { int tag; struct node *l, *r; }; struct intnode { int tag; int val; }; But it's really ugly to use. If you have an expression represented in this AST like 'a(b(c+d))' and you want to access 'd', you need to do this: struct node *n; int d = ((struct intnode *)(((struct infixnode *)(((struct infixnode *)(((struct infixnode *)(((struct infixnode *)n)->r))->r)))))->val; But if you use unions: union node { struct infixnode infix; struct floatnode floatval; struct intnode intval; }; Then you can say this: union node *n; int val = n->infix.r->infix.r->infix.r->intval.val; The same holds for C++. In C++ you could make a class hierarchy for your AST. But you still have the casting to convert to the derived types, which is just as ugly.. But you can instead make inline access functions in the base class whose sole purpose is to do this casting, you end up something like this: node *n; int val = n->infix()->r->infix()->r->infix()->r->intval()->val;