#define

What's wrong with #define? Is it considered bad programming to use it?
It should be avoided because it destroys scope rules and can lead to very cryptic error messages.

Consider the following:

1
2
3
4
5
6
#define foo 5

int main()
{
   int foo = 3;
}


This will give you a bizarre error.. something like "left side of = operator must be an lvalue" or something weird like that. Essentially the compiler is trying to do int 5 = 3;, which of course is nonsense.


Usually, the only thing you need macros for are header guards. Occasionally they have other uses, but in general you should try to avoid them.

They can often be replaced with other features which obey scope and language rules, like inline functions, templates, constant variables, etc.
Hi Da0omph,

I wouldn't use macros since they have no sense of encapsulation. I use #define in header guards but thats it. Its better to use constant global members.
Macros do have their uses - you just shouldn't abuse them by making them do stuff that's already in the language (like constants, inline functions, etc).
Yes. Save macros for when you really want to abuse the code. Using them to create your own Franken-language is always popular amongst everyone else on the coding team :)
Topic archived. No new replies allowed.