15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

602<br />

Creating Subprograms and Functions<br />

Every subprogram must have a unique name, which usually describes the<br />

purpose of that subprogram, such as Calculate_Velocity or Check-<br />

Password. The parameter list declares variables to hold any data the subprogram<br />

may need from another part of the program. For example, a simple<br />

parameter list might look like this:<br />

SUB Name (BYVAL Age AS Integer)<br />

Command<br />

END SUB<br />

The BYVAL keyword stands <strong>for</strong> By Value and means that the subprogram<br />

receives a copy of data sent to it from another part of the program. If the<br />

subprogram changes the value of that data, the new value of that data only<br />

appears in the subprogram and not in any other part of the program. The<br />

BYVAL keyword is optional in REALbasic.<br />

Instead of the BYVAL keyword, you could also use the BYREF keyword,<br />

which stands <strong>for</strong> By Reference, such as<br />

SUB Name (BYREF Age AS Integer)<br />

Command<br />

END SUB<br />

When accepting data By Reference, a subprogram can change the value of<br />

that data, which can affect the rest of the program.<br />

A function is a special version of a subprogram that always returns a single<br />

value. To create a function, use the FUNCTION keyword, such as<br />

FUNCTION Name (Parameter list) AS Datatype<br />

Command<br />

RETURN value<br />

END SUB<br />

The two main differences between a function and a subprogram (procedure)<br />

are that a function needs to include the RETURN keyword and needs to be<br />

defined as a specific data type.<br />

The RETURN keyword defines a variable that contains a specific value that<br />

the function calculates. This value gets returned back to another part of the<br />

program. Because a function represents a single value, you must define the<br />

data type of this value, such as an Integer or a String.

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

Saved successfully!

Ooh no, something went wrong!