#DEFINE?????????????

Started by
5 comments, last by GameDev.net 24 years, 5 months ago
Quick answer, yes, you could replace #define values with consts in most cases however, unlike a const a #define can take on a variety of non-variable like formats. i.e. you don't just have to use #define for numeric values, because unlike const the compiler parses through your code replacing each #define with precisely what you stated.
#define MAX_PEOPLE (10)
...
int myInt = MAX_PEOPLE

will be replaced with
int myInt = (10)

This can be a problem with macro definitions.
A macro is simply a #define which replaces a statement with a piece of code
#define sqr(x) (x*x)
sqr(10) is replaced by (10*10)
This is used for inline code avoiding the overhead of calling a function and passing variables (a compartitvely large overhead for a small function)
The problem arises if you think that macros act the same as functions
sqr(5 + 10)
does not equal
sqr(15)
because it is precisely replaced with
(5 + 10 * 5 + 10)
As + has a higher order of precedence this amounts to
(5 + (10 * 5) + 10)
or
65
not the 15^2 or 225 you wanted

Another use for #defines is removing or altering code for compile.
Simply
#ifdef DEBUG
printf("Debug");
#else
printf("Not debug");
#endif
compiles the first case if the statement
#define DEBUG
is within scope or in your compiler settings
or the second case if it is not.
This allows you to make sure certain code is only compiled to help you debug and never slows down the final release version.
This is far more than you asked but I hope it helped (more than confused at least)

Advertisement
A side note (MikeD: I'm sure you know this, your post just doesn't say ):

When using macros, ALWAYS, embrace the parameter in ( ), I.e.

#define sqr(x) ((x)*(x))

To avoid the problem described...

/Niels

<b>/NJ</b>
I did know that and that's how I solved the sqr problem which I had myself only a coupla months back (and I'm a so called professional )
I was just too stupid to actually give the answer to the problem....
hmm....there's still a problem. consider this:
a = sqr(i++);
means:
a = ((i++)*(i++));

instead of macros, use inline function is safer.

Good point, I'd forgotten about how, however much design you've done, code will always get the better of you.
Uh, im not very familiar with this #define, but from what i can deduct its something like const. Well anyway in the book Tricks of the windows game programming bla bla blah. They use #define, i was wondering can i change that to const???
Some part of me thinks that's what makes programming fun.... Another part of me is telling the first part to shove it.... Do I sound schizo?

/Niels

<b>/NJ</b>

This topic is closed to new replies.

Advertisement