What is the benefit of using #define to declare a constant?

Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program.  For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows: #define PI 3.14159 Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.  

Showing Answers 1 - 7 of 7 Answers

sundar

  • Nov 3rd, 2006
 

#define is used for declaring constants.

if we use #define the value of that constant is directly replaced by that name of the constant.

here time is reduced.

 

When you define constant variable there is possiblity that it's value may get changed in the program accidently by use of say pointer, but if you define constant by #define it's value can't be changed. This is also one of the benifit of using #define.

  Was this answer useful?  Yes

kbjarnason

  • Jul 2nd, 2010
 

I see examples such as #define PI 3.1415, which show _how_ you can use a define to declare a constant, but don't exactly explain _why_ you'd want to do this, rather than, say, const double PI = 3.1415;

Here's one example: defining array sizes.  Suppose I want to define an array (and its subsequent handling code) in such a way that it's easy to modify later.  Sounds like a perfect case for a nice const, right?

const int ARR_SIZE = 32;
...

int myarray[ARR_SIZE];


Oops.  It don't work.  It might in C99, with the new VLA support, but it does not work in C90.  The reason is that despite being called a "const", it's not actually a constant.  C's a bit weird in a few spots, and this is one of them.  Instead, I'd use a define:

#define ARR_SIZE 32
....
int myarray[ARR_SIZE];

Voila, works like a charm.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions