Path: utzoo!mnetor!tmsoft!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!news.cs.indiana.edu!ux1.cso.uiuc.edu!csrd.uiuc.edu!sp64.csrd.uiuc.edu!bliss From: bliss@sp64.csrd.uiuc.edu (Brian Bliss) Newsgroups: comp.lang.c Subject: Re: When do you use const Keywords: const, #define, C Message-ID: <1991Feb1.203935.18927@csrd.uiuc.edu> Date: 1 Feb 91 20:39:35 GMT References: <1220@tredysvr.Tredydev.Unisys.COM> Sender: news@csrd.uiuc.edu (news) Reply-To: bliss@sp64.csrd.uiuc.edu (Brian Bliss) Organization: Center for Supercomputing Research and Development Lines: 51 In article <1220@tredysvr.Tredydev.Unisys.COM>, paul@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. |> |> Paul Siu |> paul@tredysvr.tredydev.unisys.com because you can take the address of a variable declared as constant, but you can't take the address of a hard-coded constant. You can also declare const int *x; which means that the value to which x points will not be changed. therefore if you have: func f (const int *x, int *y); then once the comipler fetches the value of *x, it need not fetch it again in the subroutine, means it is constant. if it were not constant, then we could potentially modify the value of *x by assigning through *y (if x == y), and the compiler would need to recalculate *x every time it was needed (if *y or any global variable has been modified since the last calculation of *x). Not only that, but the type information for a symbol declared as const is included in the dbx symbol table information, and you can refer to that constant by name when debugging. What I welcome even more that the const declaration is the volatile declaration. Anyone who does parallel programming has run into the bug at a syncronization point: while (x); which means "wait unitl another processor changes the value of x to nonzero". unfortunately, many compilers do not re-fetch the value of x from memory each iteration of the loop (common subexpression elimination across loop iterations), and therefore go into an infinite loop. declaring x as volatile should tell the compiler that it's value can be changed without the current process doing so. bb