#define or const?

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Dec 2004
Posts: 27
Reputation: odee is an unknown quantity at this point 
Solved Threads: 0
odee odee is offline Offline
Light Poster

#define or const?

 
0
  #1
Feb 7th, 2005
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?
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 4,416
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 248
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: #define or const?

 
0
  #2
Feb 8th, 2005
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.
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 27
Reputation: odee is an unknown quantity at this point 
Solved Threads: 0
odee odee is offline Offline
Light Poster

Re: #define or const?

 
0
  #3
Feb 8th, 2005
hey thanks...
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC