944,171 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 13931
  • C RSS
Feb 7th, 2005
0

#define or const?

Expand Post »
should i use #define or const in declaring constant variables?? which one is better? when should i use #define or const?

for example when i declare a hexadecimal (0x01), should i use #define or const?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
odee is offline Offline
27 posts
since Dec 2004
Feb 8th, 2005
0

Re: #define or const?

Quote originally posted by odee ...
should i use #define or const in declaring constant variables?? which one is better? when should i use #define or const?

for example when i declare a hexadecimal (0x01), should i use #define or const?
It depends.

A constant variable will take up space, and finding its value may take more time. A #define will, as per the example you have shown, simply be a text replacement of the value 1 in source code. That is, it is directly encoded into the executable.

But with a const, you get type checking. This may be an advantage to prefering it.

For array sizes, I prefer neither. Using sizeof array / sizeof *array will get you the number of elements when array is in scope, and where it isn't it IMO should be passed as a parameter.

For bit masks, I would use a #define, if not a macro like this.
  1. #define BIT(x) (1 << (x))
For data types other than integers, it too depends -- but I generally try to minimize the number of #defines in my code.
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Feb 8th, 2005
0

Re: #define or const?

hey thanks...
Reputation Points: 10
Solved Threads: 0
Light Poster
odee is offline Offline
27 posts
since Dec 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: sound file switching
Next Thread in C Forum Timeline: needed recursion help





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC