[vox-tech] C question: global vs local const

Jeff Newmiller vox-tech@lists.lugod.org
Fri, 18 Jan 2002 08:57:00 -0800 (PST)


On Fri, 18 Jan 2002, Mark K. Kim wrote:

> 
> Keywords: global, local, c, variables, const
> 
> On Fri, 18 Jan 2002, Peter Jay Salzman wrote:
> 
> > does this apply to static variables too?  i have a situation where a
> > function is called many times over:
> >
> > void function( ..., long double dr)
> > {
> > 	long double variable = expensive_calculation * dr;
> > 	...
> > }
> >
> > i'd like to declare variable as static, since both expensive_calculation
> > and dr remain constant through the entire program.  i can't declare dr
> > as being global because it depends on other parameters that need to be
> > calculated at run time (but otherwise don't change).
> 
> Hmmm... ummm... hmmm...  Think, think...
> 
> Yes.  If they aren't calculated at compile time, then you need some way to
> tell whether a function call during runtime is the "first call".  This
> would have to be something like:
> 
>    int function(int arg)
>    {
>       if(first_call())
>       {
>          /* initialize static variables */
>       }
> 
>       blah blah...
>    }
> 
> This adds hidden overhead to a function call, which would be a no-no for C.

ANSI C added the ability to initialize auto variables in functions to the
K&R language.  Constant initialization of auto variables was considered a
big step forward in usability at the time. :)

Initializers for static variables inside functions may be non-constant
expressions in C++, because the compiler automatically generates the
"if" code. 

Static variables at module scope (outside functions, with no
external linkage) are automatically pre-initialized to zero in C.  This
fact can be used to setup a flag for the function to test to see whether
that function has been called yet.

(In C++, initialization of variables at global scope is complicated by the
allowance for user-defined constructors.  These are called by startup code
prior to calling main, in the sequence they were declared in within
modules, and those sets of constructors for each module are called in
implementation- defined sequence (you can't determine whether the module
constructors from module A will be called before those in module B within
the language).)

> -Mark (making it up as he goes...)

Pretty good jazz. :)

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil@dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...2k
---------------------------------------------------------------------------