Computer Science › Section G · Programming languages › Topic G.3

Procedural units: functions and parameters

Large programs stay manageable only because they are built from small, named pieces that can be written, tested and reused on their own. Functions are those pieces, and parameters are what make one function useful for many different inputs.

Why break programs into functions

A function, also called a procedure, subroutine or method depending on the language, is a named block of statements that performs one task. Writing a task once and calling it by name has three benefits. It avoids copying the same code into many places, so a fix is made once. It hides detail, so a reader of the main program sees steps such as read_scores(), sort_scores() and print_report() rather than hundreds of lines. And it lets each piece be tested separately. This is abstraction at work: a function generalises a task, and parameters let it be applied to whatever data is needed.

Calling and returning

When a program reaches a call, control transfers to the start of the function. The function's statements run, and when it finishes, control returns to the point just after the call, so the calling program carries on where it left off. The same function can be called from many places and many times; each call starts fresh. A function can call other functions, and even itself, which is recursion, as in the topic "Recursive structures: binary search". At machine level, the processor must remember a return address for each active call, which is why calls are slightly more costly than plain statements.

Local variables and scope

A variable created inside a function is local: it exists only while that function runs and can be used only inside it. The part of a program where a name can be used is called its scope. Local variables mean two programmers can both use a name such as i or total in their own functions without interfering. A global variable is visible throughout the program. In Python, a function may read a global freely, but assigning to that name inside the function creates a new local variable unless the function first declares global name. Heavy use of globals makes programs hard to reason about.

Worked example: tracing scope

Python code: line 1, x = 10. Line 2, def f(): with two indented lines, x = 3 and return x * 2. Line 5, print(f(), x). Steps: (1) Line 1 creates a global x holding 10. (2) The def statement only defines f; nothing inside it runs yet. (3) print first calls f(). Inside f, x = 3 creates a local x, separate from the global one. (4) f returns 3 * 2 = 6, and its local x disappears. (5) print then looks up x in the global scope, where it is still 10. Output: 6 10. Assigning to x inside f never touched the global x.

Formal and actual parameters

The names listed in a function's header are its formal parameters: placeholders for data the function will receive. The values supplied in a particular call are the actual parameters, also called arguments. In def describe(name, age): return name + " is " + str(age), the formal parameters are name and age. The call describe("Ana", 15) matches arguments to parameters by position, giving "Ana is 15". Swapping them, describe(15, "Ana"), puts a number where text is expected, and Python raises a TypeError. Python also allows keyword arguments, describe(age=15, name="Ana"), which match by name instead of position.

Passing by value and by reference

Languages differ in how arguments reach the function. With pass by value, the function receives a copy of the data, so changes inside it cannot affect the caller's variable. C always does this: after void add_one(int n) { n = n + 1; }, calling add_one(a) leaves a unchanged. With pass by reference, the function is given access to the caller's variable itself, so changes are visible afterwards. C++ marks this with an ampersand, void add_one(int &n), and then add_one(a) really does increase a. Pass by value protects the caller's data; pass by reference avoids copying large structures and lets a function update its caller's variables.

Python's model: passing object references

Python does not fit either label neatly. Every argument is a reference to an object, and the parameter becomes a second name for that same object. Two consequences follow. Rebinding the parameter, as in n = n + 1 or items = [0], only changes what the local name points to, so the caller sees nothing. Mutating the object, as in items.append(99), changes the shared object, so the caller does see it. Integers and strings cannot be mutated, so functions receiving them behave as if passed by value. Lists and dictionaries can be, so a function can change them in place.

Worked example: rebinding versus mutating

Python code: def add_item(items): items.append(99), and def replace(items): items = [0]. Then nums = [1, 2], add_item(nums), print(nums), replace(nums), print(nums). Steps: (1) nums names a list holding 1 and 2. (2) In add_item, items is a second name for that same list, and append changes the list itself. (3) The first print shows [1, 2, 99]. (4) In replace, items = [0] makes the local name point to a brand-new list; the original list is untouched. (5) The second print still shows [1, 2, 99]. Rule of thumb: assignment to a parameter is local, but method calls that change an object reach the caller.

Functions that return values

Some functions perform an action, such as printing a report; others exist to compute a value, like a function in mathematics. A return statement ends the function and sends a value back to the caller, where it can be stored or used straight away: with def rect_area(w, h): return w * h, the expression rect_area(3, 4) + rect_area(2, 5) gives 12 + 10 = 22. Pascal called value-returning units functions and the others procedures. C and Java mark a no-value function with void. In Python every function returns something: one with no return statement returns None. Python programmers sometimes call value-returning functions fruitful.

Event-driven functions

Not every function is called by another statement. In a graphical interface, the code for a button is a function, called a handler, that the system runs when the button is clicked. Software built this way is event-driven: handlers lie idle until their event, such as a click, key press or timer, occurs, then run and return. Programmers often register a handler by passing the function itself as an argument, without brackets, as in a button whose command option is set to save_file. A function passed so that something else can call it later is called a callback.

Common mistakes to avoid

Confusing defining a function with calling it: def only creates it, and writing save_file instead of save_file() refers to the function without running it. Expecting a function's local variables to exist after it returns. Assigning to a global inside a Python function without declaring it global: with count = 0 outside, count = count + 1 inside raises UnboundLocalError. Supplying arguments in the wrong order. Printing a result instead of returning it, which leaves the caller with None. Assuming every language passes arguments the same way.

Key takeaways

Functions package a task under a name; a call transfers control to the function and a return brings it back to just after the call. Local variables have the function as their scope, which prevents name clashes. Formal parameters are the placeholders in the header; actual parameters are the values in a call, matched by position or by keyword. Pass by value copies, pass by reference shares, and Python passes object references, so mutation is visible but rebinding is not. Return statements send values back. Event-driven systems run handlers when events occur.

Flashcards

Flashcard

Function

A named block of statements performing one task

Also called procedure, subroutine or method.

Test your understanding

Question 1 of 5

In Python, y = 4 is set globally, then def g(): y = 9 and return y + 1 are defined. What does print(g(), y) show?

Question 2 of 5

In the C function void double_it(int n) { n = n * 2; }, what happens to a after a = 7; double_it(a);?

Question 3 of 5

In def total(price, qty): the call total(2.5, 4) is made. Which statement is correct?

Question 4 of 5

Python: def tag(d): d["seen"] = True is called as tag(info), where info = {}. What is info afterwards?

Question 5 of 5

A Python function computes a value with print(result) but has no return statement. What does the caller receive?

← Previous topicNext topic →