Main Content

Call by name v call by value

Archive - Originally posted on "The Horse's Mouth" - 2005-05-11 07:55:00 - Graham Ellis

All the programming languages that we train on provide the facility for you to write a named block of code and the call it from elsewhere - such blocks are known as subs in Perl, functions in PHP, Procs in Tcl, and functions or methods in Python. They're a vital part of any "grown up" programming system, allowing for modular coding and the re-use of common facilities between many of your programs.

Code blocks aren't used in isolation - they need to have information that they're to work on passed in, usually in the form of parameters. There are two ways of doing this.

You can pass in parameters by VALUE. If you do this, the contents of the variable are copied into the named block of code. That's a very safe way of doing things - since the value is copied in, any changes made to it within the named block of code will not cause any change to the data from which it was passed in the main code. If you like, this is rather like me handing you a photocopy of a document - no matter how much you draw all over the photocopy, you're not damaging my original.

You can pass in parameters by NAME. In a call by name system, a variable within your named block of code points to the same piece of computer memory as the variable in the calling code and if a function alters the content of a variable in a scheme such is this, it also alters the calling variable. This is like me loaning you an original document - if you draw all over it, you've damaged the only copy and it can't be recovered

So call by NAME is very much more flexible that call by VALUE - perhaps dangerously so.

Which scheme do the languages on which we provide training work?

In Perl, you're calling by name through the special list @_. It is, however, a convention to copy the contents of that variable into a named variable within your sub, thus making it look like call by value.

In PHP, you call by value by default. If you add an extra & (Ampersand) in front of the variable name in the function definition, you're telling it to pass parameters by name instead.

In Tcl, you call by value. If you need to call by name, you actually pass in the name as a value and then use the upvar command. This always takes a while to explain on the Tcl courses!

In Python, you call by name. Everything is an object, and you simply pass in a reference to the object.

In C, you're calling by value most of the time. If you preceed your called value with and ampersand (&) then you're passing in the address at which the value can be found - i.e. you're calling by name.