When do you use const

Brian Bliss bliss at sp64.csrd.uiuc.edu
Sat Feb 2 07:39:35 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.
|> 
|> Paul Siu
|> paul at 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



More information about the Comp.lang.c mailing list