When do you use const

Ray Spalding cc100aa at prism.gatech.EDU
Sat Feb 2 08:00:45 AEST 1991


In article <1220 at tredysvr.Tredydev.Unisys.COM> paul at tredysvr.Tredydev.Unisys.COM (Paul Siu) writes:
>However, what is the advantage of using const over #define?  Why was the
>reason for its addition to ANSI C.

I believe "const" was added to (a) announce objects that may be placed
in read-only memory, (b) provide possible opportunities for
optimization, and (c) provide possible opportunities for diagnostics.
These would all seem to be possible with #defines of simple constants
like 3.14 or "abc" as well.  But with "const", you can have read-only
pointers, pointers to read-only objects, and read-only structs, arrays,
etc.  You can also take the address of a "const" variable (with &), but
not of a literal constant.

Of course, the "const" keyword is also used to denote that a function
will not alter an array argument; a different usage but one that can be
checked for optimizations and violations in a similar way by a
compiler.
-- 
Ray Spalding, Technical Services, Office of Information Technology
Georgia Institute of Technology, Atlanta Georgia, 30332-0715
uucp:     ...!{allegra,amd,hplabs,ut-ngp}!gatech!prism!cc100aa
Internet: cc100aa at prism.gatech.edu



More information about the Comp.lang.c mailing list