15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

224<br />

Passing Parameters<br />

This is how the preceding subprogram works:<br />

✦ The first line defines the subprogram name — ConvertC2F — and its<br />

parameter list as accepting one Single variable called Temperature. To<br />

specify that this parameter will be passed by reference, this BASIC language<br />

example uses the ByRef keyword.<br />

✦ The second line plugs the value of the Temperature variable into the<br />

conversion equation and stores the result back in the Temperature<br />

variable, erasing the preceding value that was stored there.<br />

✦ The third line ends the subprogram. At this point, the modified value of<br />

the Temperature variable is sent back to the main program to use.<br />

Every <strong>programming</strong> language uses different ways to identify when a parameter<br />

will be passed by reference. The BASIC language uses the ByRef keyword<br />

whereas the C language uses the ampersand symbol (&) to identify parameters<br />

passed by reference. In the following C example, the a parameter is<br />

passed by value but the x parameter is passed by reference:<br />

subprogram_example (int a, float &x);<br />

If you had the following BASIC subprogram:<br />

SUB ConvertC2F (ByRef Temperature as Single)<br />

Temperature = ((9/5) * Temperature) + 32<br />

END SUB<br />

You could call that subprogram like this:<br />

DIM Temp AS SINGLE<br />

Temp = 12<br />

PRINT “This is the temperature in Celsius = “; Temp<br />

ConvertC2F (Temp)<br />

PRINT “This is the temperature in Fahrenheit = “; Temp<br />

END<br />

Running this program would produce the following:<br />

This is the temperature in Celsius = 12<br />

This is the temperature in Fahrenheit = 53.6<br />

Notice that right be<strong>for</strong>e calling the ConvertC2F subprogram, the value of<br />

the Temperature variable is 12, but the ConvertC2F subprogram changes<br />

that value because the subprogram was passed the Temperature value by<br />

reference. What happens if you run the same program except change the<br />

subprogram to accept parameters passed by value instead, such as

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!