Initialization of Static variables

R

riva

Why the static variable in a function should be initialized by a
constant? Why not any normal variable.
 
U

user923005

Why the static variable in a function should be initialized by a
constant? Why not any normal variable.

Static variables are initialized to NULL or zero as appropriate
automatically.
If you want to set it to a specific value other than zero, then you
should do that. Of course, that is also true for automatic variables.
 
R

Richard Heathfield

riva said:
Why the static variable in a function should be initialized by a
constant? Why not any normal variable.

2.1.2 Execution environments

"[...] All objects in static storage shall be initialized (set to their
initial values) before program startup."

Before program startup, the value of a "normal variable" (as you call it)
is not known, so clearly it cannot be used for initialising a static
object's value.
 
C

Chris Dollin

riva said:
Why the static variable in a function should be initialized by a
constant? Why not any normal variable.

Static variables are initialised /once/, before the program
proper starts executing. There are no "normal" (I'm taking
you to mean "automatic") variables to be had.

If you want to set your static to a dynamic value, you
can use a common-or-garden assignment statement.

Since one of the points of a static variable is that it
retains its value between calls of its enclosing function,
having it re-initialised on each call would be ... unhelpful.
 
C

CBFalconer

riva said:
Why the static variable in a function should be initialized by a
constant? Why not any normal variable.

Because the static variable is not 'initialized' by code. The
value is set in an image of the static structures, and loaded from
that. That initialization method can't reach the 'normal variable'
value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,157
Latest member
MercedesE4
Top