What would be the difference between say doing this?
#define NUMBER 10
and
float number = 10;
In what circumstances should I use one over the other?
#define NUMBER 10
Will create a string replacement that will be executed by the preprocessor (i.e. during compilation).
float number = 10;
Will create a float in the data-segment of your binary and initialize it to 10. I.e. it will have an address and be mutable.
So writing
float a = NUMBER;
will be the same as writing
float a = 10;
whereas writing
float a = number;
will create a memory-access.
As Philipp says, the #define
form creates a replacement in your code at the preprocessing stage, before compilation. Because the #define
isn't a variable like number
, your definition is hard-baked into your executable at compile time. This is desirable if the thing you are repesenting is a truly a constant that doesn't need to calculated or read from somewhere at runtime, and which doesn't change during runtime.
#defines
are very useful for making your code more readable. Suppose you were doing physics calculations -- rather than just plonking 0.98f into your code everywhere you need to use the gravitational acceleration constant, you can define it in just one place and it increases your code readability:
#define GRAV_CONSTANT 0.98f
...
float finalVelocity = beginVelocity + GRAV_CONSTANT * time;
EDIT
Surprised to come back and find my answer and see I didn't mention why you shouldn't use #define
.
Generally, you want to avoid #define
and use constants that are actual types, because #define
s don't have scope, and types are beneficial to both IDEs and compilers.
See also this question and accepted answer: What is the best way to create constants in Objective-C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With