Reputation: 103
Now, bear with me, I'm new to c++. While following an online tutorial for c++, it mentioned that all #define
is used for is to define a constant, like this.
#define RANDOM_CONSTANT 288
What I'm confused about is, why can't it just be done by creating a variable like this?
int RANDOM_CONSTANT = 288;
Does #define
have any other applicable uses other than defining constants?
Upvotes: 1
Views: 158
Reputation: 148
#define
defines MACROs, not constants. #define
, for example, may have certain parameters:
#define A(i) printf("%d", i)
Upvotes: 2
Reputation: 3706
There seem to be two issues to address here:
#define
useful for?The answers to which are:
#define
can do more complicated things then just replace a number with a name. It can actually take parameters. For example: #define getmax(a,b) a>b?a:b
does not merely replace a number with a name.
Two parts: First, constants cannot be edited by the program (hence the name ;) ) so this in a way is a sort of safe guard. Second, it is precompiled not a variable so it takes no storage space and doesn't need to be looked up making it more efficient.
Upvotes: 1
Reputation: 14225
#define
is used to define some of the text substitutions performed by the preprocessor. If you write
#define foo 417
and then refer to foo
in your program, all instances of the identifier foo
will be turned into the number 417
. (But foo4
will remain as foo4
, for instance.)
#define twice(x) x,x
then an occurrence of twice(417)
in your program will turn into 417,417
.
If I were you, I wouldn't worry about it too much at this stage.
Upvotes: 2
Reputation: 4439
#define
allows you to change the environment before compile time. So for example, you can use #if RANDOM_CONSTANT
will allow you to modify what code gets compiled.
This is highly useful so that you can conditionally compile, for example, debugging features based on whether or not certain things were #define
d or not.
Upvotes: 2