Rexx - Subroutines


Advertisements


In any programming language, the entire program is broken into logical modules. This makes it easier to write code that can be maintained easily. This is a basic requirement for any programming language.

In Rexx, modules can be written using Subroutines and functions. Let’s look at the subroutines in detail.

Defining a Subroutine

The syntax of a function declaration is as follows −

FunctionName: 
   Statement#1 
   Statement#2 
   …. 
   Statement#N

Where,

  • FunctionName − This is the name assigned to the subroutine.

  • Statement#1 .. Statement#N − These are the list of statements that make up the subroutine.

The following program is a simple example showing the use of subroutines.

/* Main program */ 
call add 
exit 
add: 
a = 5 
b = 10 
c = a + b 
say c 

The following things should be noted about the above program −

  • We are defining a subroutine called add.

  • The subroutine does a simple add functionality.

  • The exit statement has to be used to signify the end of the main program.

The output of the above program would be as follows −

15

Working with Arguments

It is also possible to work with arguments in Rexx. The following example shows how this can be achieved.

/* Main program */ 
call add 1,2 
exit 
add: 
PARSE ARG a,b 
c = a + b 
say c

The following things should be noted about the above program −

  • We are defining a subroutine called add which takes on 2 parameters.

  • In the subroutines, the 2 parameters are parsed using the PARSE and ARG keyword.

The output of the above program would be as follows −

3

Different Methods for Arguments

Let’s look at some other methods available for arguments.

arg

This method is used to return the number of arguments defined for the subroutine.

Syntax

arg() 

Parameters − None

Return Value − This method returns the number of arguments defined for the subroutine.

Example

/* Main program */ 
call add 1,2 
exit 
add: 
PARSE ARG a,b 

say arg() 
c = a + b 
say c 

When we run the above program we will get the following result.

2 
3 

arg(index)

This method is used to return the value of the argument at the specific position.

Syntax

arg(index)

Parameters

  • Index − Index position of the argument to be returned.

Return Value − This method returns the value of the argument at the specific position.

Example

/* Main program */ 
call add 1,2 
exit 
add: 
PARSE ARG a,b 

say arg(1) 
c = a + b 
say c 

When we run the above program we will get the following result.

1 
3 


Advertisements