Functions that Initialize Memory

After we have developed contracts and purpose statements for the state variables of a program, we immediately define a function that sets the state variables to proper values. We call this function an <#68229#><#45338#>INITIALIZATION FUNCTION<#45338#><#68229#> or an <#68230#><#45339#>INITIALIZER<#45339#><#68230#>. A program's <#68231#><#45340#>initializer<#45340#><#68231#> is the first function that is used during an execution; a program may also provide other means to invoke the initializer. For our current examples, the initializers are straightforward. Here is one for the address-book example:
<#71715#>;; <#68232#><#45345#>init-address-book<#45345#> <#45346#>:<#45346#> <#45347#><#45347#><#45348#>-;SPMgt;<#45348#><#45349#><#45349#> <#45350#>void<#45350#><#68232#> <#71715#>
<#45351#>(d<#45351#><#45352#>efine<#45352#> <#45353#>(init-address-book)<#45353#> 
  <#45354#>(set!<#45354#> <#45355#>address-book<#45355#> <#45356#>empty))<#45356#> 
The one for traffic-light is equally trivial:
<#71716#>;; <#68233#><#45364#>init-traffic-light<#45364#> <#45365#>:<#45365#> <#45366#><#45366#><#45367#>-;SPMgt;<#45367#><#45368#><#45368#> <#45369#>void<#45369#><#68233#> <#71716#>
<#45370#>(d<#45370#><#45371#>efine<#45371#> <#45372#>(init-traffic-light)<#45372#> 
  <#45373#>(set!<#45373#> <#45374#>current-color<#45374#> <#45375#>'<#45375#><#45376#>red))<#45376#> 
In setting <#68234#><#45380#>current-color<#45380#><#68234#> to <#68235#><#45381#>'<#45381#><#45382#>red<#45382#><#68235#>, we follow a conventional rule of engineering to put devices into their least harmful state when starting it up. At first glance, these initializers don't seem to add much to our programs. Both set the respective state variables to the values that are their defined values. For both cases, however, it is easy to see that the initializer could do some additional useful work. The first one, for example, could create and display the graphical user interface for an address book; the second one could create and display a canvas that displays the current state of the traffic light.