No defines?

I'm told that defines are to be avoided in general. Why would the following be inappropriate?

1
2
3
4
5
//#define DEBUG

#ifdef DEBUG
cout << "..." << endl;
#endif 
There's nothing wrong with your code. #defines are useful in some situations (eg. include guards: http://www.cplusplus.com/articles/Gw6AC542/ ) but can cause problems in some too, eg.:
1
2
3
4
5
6
7
#define PI 3.14

int main()
{
const int PI=3.14; // will become const int 3.14=3.14; which will not compile
}[/code

1
2
3
4
5
6
7
8
string PI="Pi is equal to 3.14";

#define PI 3

int main()
{
cout <<PI<<endl; // will print 3
}
Last edited on
This whole "no define" stuff is basically mostly directed at practices like using defines as constants or inline functions
1
2
3
4
5
6
7
8
9
10
11
//#define square(x) x*x -- bad, use
template<typename T>
auto square(x) -> decltype(x*x)
{
 return x*x;
}
//instead

//#define PI = 3.14 -- bad, use
const float /*or double, or whatever*/ PI = 3.14;
//instead 


The reason being that macros actually replace text, and thus don't behave like you'd expect them too, and can also cause various unintended side effects.
Last edited on
Topic archived. No new replies allowed.