r/C_Programming • • 8d ago

Tidy translucent typedefs

https://tavianator.com/2026/translucent_2.html

Recently discovered a nice way to get custom warnings with Clang, so I wrote it up.

35 Upvotes

6 comments sorted by

7

u/Accurate_Appeal_3110 8d ago

This is really neat! Could be really useful on enums to prevent implicit conversions to and from its underlying type, like C++'s enum classes

4

u/tstanisl 7d ago

Interesting.

I've been looking for a way to annotate types with some form of attributes to express additional semantics like "owned", "sized", "stb_vector", etc. And some means of defining rules if the gaining/dropping attribute requires an explicit cast. I hoped to find some popular extensions but I could not find a good one. Using alignment requirements is definitely a bit scary hack but it gets job done for most cases. thank you

2

u/imaami 3d ago edited 3d ago

You could try using C23 combined with the empty struct GNU extension (works in Clang too), i.e. -std=gnu23:

struct str {
	char const *imm;
	struct{} tag[5];
	char       *mut;
};

^ Here the tagmember adds no padding between the two other members, and also sizeof (struct str){}.tag == 0 and _Countof((struct str){}.tag) == 5 are both true. Not at all sure what use this would be to you, if any, but it's an interesting feature.

PS: I only now realized that the mutable/immutable pointer pair is actually more useful as union members, but that wouldn't make sense for this particular example, so meh - it is what it is.

PPS: And now I realized who I'm replying to. I don't think any of this is new to you. :D

2

u/tstanisl 3d ago

Actually, it is quite enlightening. The empty struct is not in C standard yet but the feature is expected for C2Y. The sizeof of objects derived from empty structs behaves quite surprising:

See godbolt.

struct X {} x[5];

struct Y {
    int _;
    struct X x;
    struct X x3[3];
} y;

int sx = sizeof x;
int sx0 = sizeof x[0];
int cx = _Countof x;
int syx = sizeof y.x;
int syx3 = sizeof y.x3;
int cyx3 = _Countof y.x3;

What I got is:

"sx" :  4
"sx0" : 4
"cx"  : 5
"syx" : 4
"syx3": 4
"cyx3": 3

It looks that _Countof works as expected. But sizeof empty struct and an array of empty struct is the same! I've always expected that empty structs behaves like there was a single char or int in it. But they behave in much more bizarre way.

Thank you for pointing that.

1

u/bacmod 8d ago

Give me a source to run it.

4

u/tavianator 8d ago

You can copy the snippets from the post to try it out, or see https://github.com/tavianator/bfs/commit/d0e87c0f9d3baf4cacd06db6f8f9273866308a52