5

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253

3 Answers3

14
#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.

Philipp T.
  • 793
  • 4
  • 13
  • It should also be noted that putting `float a = 10;` (or whatever) within a header file will likely lead to duplicate symbol errors when linking. Using a `#define` won't, though. – trojanfoe Nov 28 '15 at 12:38
4

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 #defines 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

Community
  • 1
  • 1
occulus
  • 16,959
  • 6
  • 53
  • 76
0

"#Define" is actually a preprocessor macro which is run before the program starts and is valid for the entire program

Float is a data type defined inside a program / block and is valid only within the program / block.