| | |
#define or const?
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
•
•
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?
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.
C Syntax (Toggle Plain Text)
#define BIT(x) (1 << (x))
"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
![]() |
Similar Threads
- strings, arrays, length program (C++)
- Program does not declare win or lose (C++)
- Initializing a member of a class with another const/destructor! (C++)
- help my first game! (C++)
- random matrix generation (C)
Other Threads in the C Forum
- Previous Thread: sound file switching
- Next Thread: needed recursion help
| Thread Tools | Search this Thread |
Tag cloud for C
adobe ansi api array arrays bash binarysearch centimeter char character convert copyanyfile copypdffile cprogramme createcopyoffile createprocess() csyntax directory dynamic feet fflush file floatingpointvalidation fork frequency getlasterror getlogicaldrivestrin givemetehcodez global graphics gtkgcurlcompiling hardware highest homework i/o ide inches infiniteloop initialization interest kilometer license linked linkedlist linux linuxsegmentationfault list logical_drives match matrix meter microsoft motherboard multi mysql oddnumber odf open opendocumentformat openwebfoundation pattern pause pdf pointer pointers posix power problem program programming pyramidusingturboccodes read recursion recv recvblocked repetition scanf scheduling segmentationfault send shape single socketprograming socketprogramming stack standard strchr string strings structures suggestions system test testautomation unix urboc user voidmain() win32api windows.h






