Live data from Hacker News

How to properly use macros in C

pmihaylov.com

1–10 of 52 posts

Re: How to properly use macros in C

#6
The golden rule of macros is "always read the definition of macros before using." If you know it's a single value you're probably fine `#define MASK 0xf7`, but if it's a function macro or a normal macro that you know is doing more than inserting a literal in your code, it's best to glance at the macro to see what it does. Macros are useful for writing "shorthand C", but C should not be turned into a DSL, so you should think in actual C by converting the "shorthand C" in your head as you read/write it.

Re: How to properly use macros in C

#8
If you're going to write a long lecture to people, it's helpful to do some Googling to fact-check your own understanding.

The claim that macros do not exist in other languages is incorrect. Every sensible assembly language compiler has macros to help the programmer with boilerplate.

The claim that multiline macros are a problem is correct. Suggesting that a workaround is to use a naming convention for such macros is crazy-talk. There is a time-honored pattern you use to fix this in the macro itself: wrap the macro with "do { } while (0)".

Re: How to properly use macros in C

#9

    One strange phenomenon when coding in C is using macros. This is not something which can be seen in other programming languages (other than C++).
This is false. Lisp is a language, or rather, a family of languages, where macros play a giant role, and the author does not seem to mention them.

But again, Lisps generally have more powerful macros than C does - they allow for arbitrary compile-time computation.

Post reply on HN