q for the C hackers
Tom Fogal
tfogal at io.iol.unh.edu
Tue Aug 19 09:13:38 EDT 2003
sorry, again. Always forget to change the 'To:' to the list...
------- Forwarded Message
To: Erik Price <erikprice at mac.com>
Subject: Re: q for the C hackers
In-Reply-To: Your message of "Mon, 18 Aug 2003 20:13:05 EDT."
<E7B260C2-D1D9-11D7-A2C1-00039351FE6A at mac.com>
Date: Tue, 19 Aug 2003 09:10:42 -0400
From: Tom Fogal <tfogal at io.iol.unh.edu>
> When I want to define a constant value in Java, such as a magic number,
> I usually use "public static final":
>
> public static final int NUMBER_OF_UNITS = 8;
>
> However, what is the convention in C? There seem to be two fine ways
> of doing it -- using the preprocessor, or the const keyword:
>
> #define NUMBER_OF_UNITS 8
>
> const int NUMBER_OF_UNITS = 8;
>
the normal 'C' (as opposed to C++) convention is to use #defines.
the difference between the two is that the define is replaced with its value
by the C preprocessor, before any code is compiled. The actual 'text' section
of your executable/binary should be where the number '8' would show up,
although i dont think that behavior is defined by the C standard.
the const int way stores the variable in read only memory, and thus, IMO is a
waste of memory. Also, it would be required to do a memory lookup when
accessing the value.
> I'm just interested in hearing about whether one is more appropriate
> than the other in some contexts. Thanks.
Generally, I would use #defines for anything but function parameters.
Passing things as a constant reference (const type &val) is a good way to
avoid passing a large value without the overhead of actual passing it.
Unfortunately, references do not exist in C alone (they were introduced in C++)
Finally, I've never actually heard of 'const' in C. I know that it was
introduced with C++, although i would not be surprised to see later editions
of the C standard included it.
It is not in K&R ('the white book'), IIRC.
HTH,
- -tom
------- End of Forwarded Message
More information about the gnhlug-discuss
mailing list