Search code examples
c++assemblycompiler-optimizationcpu-registersunions

Do Unions prevent the use of register variables


In Agner Fog's Optimizing Software in C++ book he has the following advice (Page 94)

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.


Solution

  • 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.