#define are nice to use if you are entering the
IOCCC contest :->
Otherwise, they are useful for dynamically chosing portions of your code to compile.
say you have :
...
//very important code
#ifdef DEBUG_MODE
cerr<<"Something to help me debug this program\n";
#endif
...
now all you have to do is to put a #define DEBUG_MODE at the beginning of your file, and all statements such like the one above wont be compiled. The difference between this and something like a command line argument would be that the code wouldnt be COMPILED at all, meaning the program would take less space, and essentially be faster.
similarly, you could have something like
#ifdef DOS_COMPILE
//something for DOS specific system
#elif WIN95_COMPILE
//something else
#elif WIN2K_COMPILE
//and something even different
#endif
you get the idea, depending on what you #define at the beginning of your file, only one portion of code will be compiled.
it's actually pretty cool.
another useful thing (and you'll see that happen often in visual C++ if you have large projects), is to avoid putting the same stuff several times.
namely, you might need a particular header file for some file.
but imagine that you also need that particular header file in one of the other header files called; say you have :
types.h is a file that define a few essential types for your project. and globals.h is a file with a few globals.
now, globals.h has a #include "types.h" in it.
Now, imagine you are coding a new file where you make use of those types and globals.
You could include only types.h knowing that it itself include globals.h , right ?
Yes, but trust me, it's a real bad idea.
The nice way is this.
In your header files you put (after any necessary #include statements)
//TYPES_H is for types.h, but you could put anything else, and you have to put something different for each header file.
#ifndef TYPES_H
#define TYPES_H
//type all your stuff
#endif
That's it. Now when you include types.h in any file of your project, the compiler checks if the #define exists.
If it already exists, it means that all the code inside the #ifndef ...#endif has been processed, hence has already been included
Otherwise, it #define what it needs, and all the code gets compiled.
Nice, hey ?
I wish I had known that when I was in first year...
Sancte Isidore ora pro nobis !
[EDIT] Just fixing the link. Use "< / a >" to close instead of "< / href >"
[edited by - michalson on May 15, 2002 11:25:44 AM]
-----------------------------Sancte Isidore ora pro nobis !