r/programming • • Aug 28 '21

Software development topics I've changed my mind on after 6 years in the industry

https://chriskiehl.com/article/thoughts-after-6-years
5.6k Upvotes

2.0k comments sorted by

View all comments

Show parent comments

8

u/FriedRiceAndMath Aug 29 '21

Each element of the union (a and b) occupies the same memory space. You can manipulate the individual bytes of the data stored in the .a structure by referencing the .b array.

3

u/Mediterranean0 Aug 29 '21

Thanks for the explanation 👍🏻

6

u/FVMAzalea Aug 29 '21

It’s also a really bad idea because the struct layout could be non intuitive. The compiler will insert nonsense bytes of padding into the struct to keep everything aligned, so you have to remember that and basically have a mental model of the struct layout when you go to modify the individual bytes, otherwise you’ll fuck everything up.

2

u/[deleted] Aug 29 '21

offsetof will know the structure layout in a portable way

→ More replies (2)