Steve Johnson
Steve Johnson

Reputation: 103

What exactly is #define useful for?

Now, bear with me, I'm new to . While following an online tutorial for , 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

Answers (4)

oleg
oleg

Reputation: 148

#define defines MACROs, not constants. #define, for example, may have certain parameters:

#define A(i) printf("%d", i)

Upvotes: 2

Bren
Bren

Reputation: 3706

There seem to be two issues to address here:

  1. What is #define useful for?
  2. Why use constants instead of variables?

The answers to which are:

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

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

tmyklebu
tmyklebu

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

inetknght
inetknght

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 #defined or not.

Upvotes: 2

Related Questions