±«Óătv

Parameter passing

There are some issues to consider when using local variables instead of global variables.

  • How can the value of a variable in one sub-program be accessible to another sub-program?
  • What happens if the value of a variable needed in more than one subprogram is to change within one subprogram but not in the main program?

The solution to these issues is to use parameter passing.

passing allows the values of local variables within a main program to be accessed, updated and used within multiple sub-programs without the need to create or use global variables.

  • a main program is set up with local variables
  • either the address of the local variable in RAM, or a copy of the value of the local variable can be passed to subprograms and functions when needed

Parameter passing by reference

If a programmer passes a parameter by reference, then the subprogram or function has direct access to the memory location holding the value of the variable.

This means that any change to the value during the execution of the subprogram would apply when the variable was next used in the main program.

Parameter passing by value

If a programmer passes a parameter by value, then a temporary second copy of the value of the variable is made and held in RAM.

This copy can be changed within a subprogram but the change would not affect the original value held in the main program’s local variable.

Drawback

The main drawback is the increased demand on RAM.

As well as having to store the original value of the local variable, it is also necessary to store a second copy in main memory as well.

Advantage

The main advantage is that the value of the original local variable is protected from accidental or unnecessary change.

Passing arrays

Around forty years ago, when high level languages were gaining popularity, the designers of these languages decided to only support passing arrays by reference.

The logic was that to pass an array by value would place too much pressure on RAM.

Arrays still tend to be passed by reference.

Some programmers create temporary pointers to identify a position in an array. These pointers can then be passed by value rather than by reference.

However, at this level it is best to understand that parameter passing by reference is used when dealing with arrays.

Programming languages

Different programming languages apply different rules when passing parameters.

In some languages it is not possible to pass by value.

Related links