What exactly is #DEFINE?

I see code all the time that has #DEFINE in it... but there's no type (i.e. integer, double, etc). What exactly is going on?
#define is a macro substitution.

When you #define something as something else, the compiler will do a copy/paste style replace in the code.

ie:

1
2
3
4
5
6
7
8
#define foo bar   // foo will be replaced with bar

int main()
{
  int bar = 10;
  foo = 5;  // the compiler will replace this line with 'bar = 5;'
  cout << bar;  // prints 5
}


Macros are generally considered "evil", because #define ignores all scope rules and therefore it's extremely easy to shoot yourself in the foot. For example:

1
2
3
4
5
6
7
8
#define main barf

int main()  // compiler replaces this with 'int barf()'
{
}

// now you will get a linker error because your program has no 'main' function
//  it only has a 'barf' function 


In C++ there are better ways to do almost anything a macro can do. About the only thing macros are good for is for include guards. See this article for explanation of what a include guard is:

http://cplusplus.com/forum/articles/10627/#msg49679
Thank you! That article was great.
Topic archived. No new replies allowed.