Hacker News new | ask | show | jobs
by 1ris 2164 days ago
Writing macros (in any language) is a way of creating an abstraction. Creating abstractions is a way of automating the job of programming, making it ideally more efficient and less error prone. This is why people usually prefer java to basic. Marcos are a way of creating abstractions that are particular suited to be "concreted" by the compiler, making them a ideal match for programming languages that seek to be "close to the metal" like C, C++ and rust.

C Macros are lacking because they are very primitive, e.g. they have not type system. They are also hardly turing complete. Its extremely hard to write a meaningful algorithm in them. IMHO the real macros of the C++ language are the templates and constexpr, althou they are limited in other ways. E.g. its hard to extend the syntax using them or do certain things like making the calling function return. They grow ever more powerful, with their own type system (concepts) and things like std::embed and static refection so they finally feel like a real language, alsbei a clumsy, pure functional language that feels alien a C++ programmer without exposure to haskell.

Rust macros are actually meant to feel like Rust, not some ad-hoc bolted on language.

1 comments

> C Macros are lacking because they are very primitive, e.g. they have not type system. They are also hardly turing complete. Its extremely hard to write a meaningful algorithm in them.

I think this may be why I'm having a hard time appreciating them. Probably half the macros I see could just be a function call. The majority of those that don't are hiding a conditional return or goto, which I find to be a net negative.

I'll probably have to use a language with good macros before I can appreciate them.

> Probably half the macros I see could just be a function call.

Yes, that particular breed of C macros would likely manifest in Rust as people just defining a new function. In Rust, you tend to see macros in places where "just make a new function" doesn't suffice for whatever reason; for example, maybe you need to define a dozen different structs that only differ by the type of one field, so instead of actually defining the struct a dozen times, you could just define the struct inside the macro and then `define_my_struct!(u8); define_my_struct!(u16);` and so on.

You also can't use Rust macros to "redefine" other unrelated pieces of code, so that's one less thing to worry about.

Your define_my_struct! actually seems useful. Thanks for that example.