3 ms·
They do have downsides, but you gloss over the main reason to use macros; they're an extremely powerful tool.
by EpicEng 12y ago
They do have downsides, but you gloss over the main reason to use macros; they're an extremely powerful tool.
- Someone1234 12y agoMeh. People are expensive, compute is cheap. If code is twice as hard to debug, you better have a darn cost saving reason to be working in inefficient language like C/C++.
- EpicEng 12y agoWell, that's not always true (thinking of the numerous times I have had to optimize code written by people with this attitude), but I wasn't speaking about performance. Macros allow you to do things in e.g. C which cannot be done via any other mechanism in the language.
- copsarebastards 12y ago> Macros allow you to do things in e.g. C which cannot be done via any other mechanism in the language. This isn't really an argument in favor of macros so much as an argument against minimally-featured languages like C. To be clear, I'm not against using macros in every case. I think a lot of the danger of macros in C comes from C's syntax: macros become a much more powerful tool when you're using a homoiconic language like Lisp. There are a few different projects which have attempted to write languages with C-like semantics and Lisp-like syntax, but sadly none have gained traction.
- jeorgun 12y agoMacros really aren't about performance, though (or at least they shouldn't be; inlining and/or constexpr are a better solution to that problem in basically every respect). They're either about simple, potentially extremely unsafe, syntax extensions (as in the article) or about using metadata that wouldn't otherwise be available (e.g. filenames/line numbers in the assert macro). Not that I think macros are a good thing– 99% of the time they're best avoided– but dismissing them because 'performance isn't important' is basically a non sequitur.
- copsarebastards 12y agoPlenty of languages provide filenames/line numbers in assertions without using macros. Furthermore, `__LINE__` and `__FILE__` style macros are a pretty safe subset of macros that aren't really representative of the problems with macros. Compare: #include <stdlib.h> #include <stdio.h> #include "my_macro_library.h" int main() { int x = 0; printf("%i", increment(x)); printf("%i", __LINE__); return EXIT_SUCCESS; } There are a ton of different implementations of an `increment` macro which are going to cause undefined behavior here. Contrast with the `__LINE__` macro: it's implemented by the compiler and has unsurprising, well-defined behavior.