Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between #Define and Float?

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?

like image 477
Josh Kahane Avatar asked Mar 05 '11 11:03

Josh Kahane


2 Answers

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

like image 83
Philipp T. Avatar answered Nov 02 '22 09:11

Philipp T.


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

like image 21
occulus Avatar answered Nov 02 '22 08:11

occulus