Googles appar
Huvudmeny

Post a Comment On: cbloom rants

"05-29-10 - Some more x64"

3 Comments -

1 – 3 of 3
Anonymous Anonymous said...

I think it's fine to use unions; just, you can't expect the various sides of the union to take up the same amount of space.

If you're relying on them taking up the same amount of space, or, in other words, expecting that you know the effective layout of the union, include a compile-time assert to verify the size of the union.

Both this and the struct alignment thing are both pretty familiar to me from writing old-school (unix-era) portable C...

May 30, 2010 at 4:45 AM

Blogger cbloom said...

"If you're relying on them taking up the same amount of space, or, in other words, expecting that you know the effective layout of the union, include a compile-time assert to verify the size of the union."

Yeah that's certainly wise, the only way I've found a lot of these problems is because I fortunately did put a lot of compiler asserts in places I was relying on weirdness, but not all the places. It also means unnamed structs and unions don't work.

"Both this and the struct alignment thing are both pretty familiar to me from writing old-school (unix-era) portable C... "

Yeah the struct alignment thing was just a brain fart. But this whole issue is giving me the heebee-jeebees about unions.

For one thing, the union has two sort of different purposes - one is just to be able to reuse some memory in two different ways depending on the state, the other is to cast through from one type to another.

For the first usage I prefer to have specifically different types. eg.

struct BSPTree_Node { ... }
struct BSPTree_Leaf { ... }

struct BSPTree_Datum
{
char flags;
char bytes[ MAX( sizeof(BSPTree_Node),
sizeof(BSPTree_Leaf) ];
};

that way you write functions that work on either a Node or a Leaf and they have no possibility of touching variables that are in the other identity.

(of course this is fucked in the new aliasing world).

For the other usage of unions, I prefer to have explicit casts as imperatives in the code so they really stand out at the point of usage to make it super clear that you are type-punning there.

But that also might be fucked so I guess I lose.

May 30, 2010 at 11:50 AM

Anonymous Anonymous said...

Yeah, the whole thing about casting through unions is new to me (well, new in the last ten years or whatever) so I'm not even used to thinking about that aspect of it.

I equivocate between using multiple structures and using unions for the "tagged-type" sort of thing.

May 31, 2010 at 1:08 PM

You can use some HTML tags, such as <b>, <i>, <a>

This blog does not allow anonymous comments.

Comment moderation has been enabled. All comments must be approved by the blog author.

You will be asked to sign in after submitting your comment.