Most people on stackoverflow say its horrible to use macros in C++. I don't get the idea behind this. I know theres alternatives in C++ but why its "wrong" ?
Asked
Active
Viewed 220 times
-1
-
Post some source/link, where you found that? – 0xF1 Sep 02 '13 at 08:34
-
1Using them is not wrong, using them wrongly is wrong (huh...) – user1233963 Sep 02 '13 at 08:35
-
There are many questions tackling this – Karthik T Sep 02 '13 at 08:35
-
http://stackoverflow.com/questions/14041453/why-preprocessor-macros-are-evil-and-what-is-the-real-alternative-c11 is a good start – Karthik T Sep 02 '13 at 08:36
-
Just two questions that basically ask the identical thing: http://stackoverflow.com/questions/18230719/why-cert-standard-pre00-cpp-says-avoid-defining-macros/18230840#18230840 and http://stackoverflow.com/questions/18373782/are-there-any-good-uses-of-macros/18373921#18373921 – nikolas Sep 02 '13 at 08:36
-
http://stackoverflow.com/questions/319452/are-all-macros-evil is one more, a search for "why are macros evil" yields many more blog posts n such – Karthik T Sep 02 '13 at 08:37
-
Macros are not evil (as well as goto and the other "scary" stuff). The only true evil is the incompetent coders. – SK-logic Sep 02 '13 at 08:43
1 Answers
2
Let see what Stroustrup says:
So, what's wrong with using macros?
Macros do not obey the C++ scope and type rules. This is often the cause of subtle and not-so-subtle problems. Consequently, C++ provides alternatives that fit better with the rest of C++, such as inline functions, templates, and namespaces.
...
And yes, I do know that there are things known as macros that doesn't suffer the problems of C/C++ preprocessor macros. However, I have no ambitions for improving C++ macros. Instead, I recommend the use of facilities from the C++ language proper, such as inline functions, templates, constructors (for initialization), destructors (for cleanup), exceptions (for exiting contexts), etc.

masoud
- 55,379
- 16
- 141
- 208