1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>4.3 Default Initialization
</title>
10 <link href=
"sx4b.html" rev=precedes
>
11 <link href=
"sx4d.html" rel=precedes
>
12 <link href=
"sx4.html" rev=subdocument
>
15 <H2>4.3 Default Initialization
</H2>
17 <p>The duration of a variable
18 (whether static or automatic)
19 also affects its default initialization.
20 </p><p>If you do not explicitly initialize them,
21 automatic-duration variables
22 (that is, local, non-
<TT>static
</TT> ones)
23 are not guaranteed to have any particular initial value;
24 they will typically contain garbage.
25 It is therefore a fairly serious error
26 to attempt to use the value of an automatic variable
27 which has never been initialized or assigned to:
28 the program will either work incorrectly,
29 or the garbage value may just happen to be ``correct''
30 such that the program appears to work correctly!
32 the particular value that the garbage takes on can vary
33 depending literally on
<em>anything
</em>:
34 other parts of the program,
35 which compiler was used,
36 which hardware or operating system the program is running on,
38 the phase of the moon.
39 (Okay, maybe the phase of the moon is a bit of an exaggeration.)
40 So you hardly want to say that a program
41 which uses an uninitialized variable ``works'';
43 but it works for the wrong reason,
44 and it may stop working tomorrow.
45 </p><p>Static-duration variables (global and
<TT>static
</TT> local),
47 are guaranteed to be initialized to
0
48 if you do not use an explicit initializer in the definition.
49 </p><p>(Once upon a time,
50 there was another distinction between
51 the initialization of automatic vs. static variables:
52 you could initialize
<dfn>aggregate
</dfn> objects,
55 if they had static duration.
56 If your compiler complains when you try to initialize a local array,
57 it's probably an old, pre-ANSI compiler.
58 Modern, ANSI-compatible compilers remove this limitation,
59 so it's no longer much of a
64 <a href=
"sx4b.html" rev=precedes
>prev
</a>
65 <a href=
"sx4d.html" rel=precedes
>next
</a>
66 <a href=
"sx4.html" rev=subdocument
>up
</a>
67 <a href=
"top.html">top
</a>
70 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
71 //
<a href=
"copyright.html">Copyright
</a> 1995-
1997
72 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>