r/C_Programming • u/alex_sakuta • May 24 '26
Discussion What if C lets us create our own attributes?
I was thinking that modern languages have a lot of features that are "clean" and hence more useful.
For example: Zig's try is a cleaner way of error handling than Rust's .unwrap imo.
There are many things that we can do using C macros and I was wondering what if we could write similar functions but using custom attributes instead.
It would lead to [[some_attr]] func() instead of some_macro(func()).
You can think of the example of try where instead of try being a macro we can use try as an attribute.
For this, attributes should be able to work with any type like macros to be useful imo.
It'll be more clean and with new features such as typeof and _Generic I believe it would change how we write C.
24
u/dkopgerpgdolfg May 24 '26
Just btw., this comparison doesn't make sense. And unwrap (and any other panic thing) isn't meant to be the go-to error "handling" in most cases.
21
u/not_a_novel_account May 24 '26
This is isomorphic to part of C++ reflection, which allows you to match on custom attributes.
At some point you keep adding things to C, you get C++. C++ itself is the result of "keep adding things to C".
9
u/somewhereAtC May 24 '26
The implementation of try implies that functions return two values -- the planned/architected value and also the exception indicator. This greatly complicates the expectation of which will or can be managed on the call-stack. When you have a zillion-gigahertz and near-infinite memory then this is ok, but most C systems are resource constrained on fairly rudimentary cpu's with good testing, so the exception handling will just waste resources.
2
u/WittyStick May 25 '26
You already can create your own attributes. C23 attributes are ignored if not supported (compiler is free to warn or error though).
You just have to implement a compiler that supports them.
2
u/iOSCaleb May 24 '26
Trying to do too much with the C preprocessor is a quick road to hell. Seeing the preprocessor as a clean way to add language features is just madness.
Swift might be a better example. Swift’s macros are able to transform code in more complex ways, and they’re expanded by the compiler rather than a preprocessor, so they get all the compiler’s safety checks.
1
u/gizahnl May 24 '26
You already can do "everything" with pre processor macros (not saying you should!). And tbh there's already a way to "try", you just have a function that returns an error code, any additional return values you'd pass out via extra out pointers.
Attributes are just a special way to instruct the compiler of something. Adding attributes wouldn't change much.
0
u/fb39ca4 May 24 '26
You could replace the C preprocessor with one that does this.
1
u/[deleted] May 24 '26
[removed] — view removed comment