Home > Mobile >  Do Unions prevent the use of register variables
Do Unions prevent the use of register variables

Time:09-27

In union is not optimal because it prevents the use of register variables

How does a union prevent the register variables being used? Running some toy examples in compiler explorer (o3) did not reveal such limitation.

CodePudding user response:

The practical answer is: it doesn't matter. Unions are only worth it when the memory saved is substantial (the example in the question only saves a few kB, which probably matters only on embedded systems). But the register comment would only matter for unions small enough that their members fit in registers. Even for embedded systems, that's several orders of magnitude difference.

Bottom line: avoid unions, until profiling shows a direct memory pressure problem, and then see if you can solve if with derived classes instead, or std::variant. union is a C solution.

CodePudding user response:

This would be an ABI specific answer, but if you had a union vs an int... and is passed to a function the union has to be pushed on the stack where an int could be passed in a register, same goes for pointers, float types, etc... but that applies to structs/class instances, so it doesn't seem like a very great concern to me... unions are codesmell out side of embedded programming, because if you are using them for something like parsing, that parser ( eg. overlayed char[] to a struct ) is only guaranteed to work if it works, struct packing is up to the compiler and even with hints it can do what it wants, also obviously a change in endianness would break every multibyte member.

In this example if you used the enum as a function param it would have to go on the stack, but a pointer to either member could be passed in a register, but ... a pointer to the enum could go in a register anyway... they just don't decay to pointers like arrays do though.

  • Related