When do you use const

Kevin D. Quitt kdq at demott.com
Sun Feb 3 05:19:48 AEST 1991


In article <1220 at tredysvr.Tredydev.Unisys.COM> paul at tredysvr.Tredydev.Unisys.COM (Paul Siu) writes:
>In ANSI C, you can define a variable as constant by preceeding it with const.
>You can for example define a double variable x that you cannot change by
>
>     const double x;
>
>However, what is the advantage of using const over #define?  Why was the
>reason for its addition to ANSI C.

    Your variable x above is pretty useless, since it has no initialized
value (and is therefore zero).  How about:

const char	*foo	= "some really long string";

    If this is #defined, and is accessed in several places, your
compiler may save multiple copies of the string.  Even if your compiler
is smart enough to make it a single instance, it won't do this over
several modules. 

  Another advantage is in the optimization phases, where the const keyword
provides more information to the optimizer.


-- 
 _
Kevin D. Quitt         demott!kdq   kdq at demott.com
DeMott Electronics Co. 14707 Keswick St.   Van Nuys, CA 91405-1266
VOICE (818) 988-4975   FAX (818) 997-1190  MODEM (818) 997-4496 PEP last



More information about the Comp.lang.c mailing list