Dale - Computer Science Illuminated 281

Dale - Computer Science Illuminated 281 - algorithm box...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
254 Chapter 8 High-Level Programming Languages We do not show a Java example because Java handles memory very differ- ently from the other three and has only value parameters. We do not show an Ada example because the compiler is free to select the most efficient parameter-passing mechanism for the given hardware or Bytecode virtual machine. Before we leave subprograms, let’s look at an example that illustrates the difference between value and reference parameters. Let’s write an algo- rithm that swaps the contents of two places in memory. Let’s call them data1 and data2 . This sounds easy enough: We just store data1 into data2 and data2 into data1 . Right? Well, not exactly. If we do this, we end up with both variables containing what was originally in data1 . We need an intermediate variable in which to store the contents of data2 before we copy data1 into it. We call this intermediate variable a local variable. It is only needed for a short while. We put the subprogram name on top of the
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: algorithm box along with its parameters. Now let’s say that the calling unit (the part of the program that wants the contents of the two places exchanged) calls Swap with data1 and data2 as parameters. Now let’s say that data1 is stored in location 0002 and data2 is stored in location 0003 . They contain the values 30 and 40, respectively. Figure 8.7 shows the content of the message board when the parameters are passed by value and passed by reference. When a parameter is a value parameter, the subprogram knows to manipulate the value on the message board. When a parameter is a reference parameter, the subpro-gram knows to manipulate the contents of the address on the message board. Should the parameters for subprogram Swap be value or reference parameters? Swap (data1, data2) Swap (Integer item1, Integer item2) Integer temp Declare local variable Set temp to item2 Set item2 to item1 Set item1 to temp...
View Full Document

This note was uploaded on 01/13/2011 for the course CSE 1550 taught by Professor Marianakant during the Fall '10 term at York University.

Ask a homework question - tutors are online