Function

On this page 7

A function is a named, reusable block of code that receives input through parameters, performs a defined task and usually returns a value to the code that called it. In programming fundamentals, the function is the basic unit of abstraction and reuse: it lets a programmer give a sequence of steps a name and then use that name instead of repeating the steps.

Depending on the language and context, functions are also called procedures, subroutines or methods. The core idea is the same in all of them: the caller hands over control together with arguments, the function runs, and control returns to the point of the call.

Anatomy of a function

A function has a definition, where it is declared once, and any number of calls, where it is used. The definition consists of a name, a parameter list, an optional return type in statically typed languages, and a body of statements. Together, the name, parameter types and return type form the function’s signature.

For example, the Python definition def area(width, height): return width * height declares a function named area with two parameters, and the call area(3, 4) passes the arguments 3 and 4 and evaluates to 12.

PartExample in PythonRole
NameareaIdentifies the function for callers
Parameterswidth, heightPlaceholders for the input values
Bodyreturn width * heightStatements that perform the task
Return valueThe product of the argumentsResult handed back to the caller
Arguments3 and 4 in area(3, 4)Actual values supplied at the call
Local variablesVariables created inside the bodyExist only during the call
Parts of a function and their roles

The distinction between parameters and arguments is a frequent source of confusion: parameters belong to the definition, arguments belong to the call.

How a function call works

When a function is called, the runtime creates a stack frame on the call stack. The frame holds the arguments, the local variables and the return address, which records where execution continues after the function finishes. When the function returns, its frame is removed and the return value is passed back.

This mechanism explains several practical limits. Each nested call adds a frame, so deep recursion can exhaust the stack and cause a stack overflow; default limits are roughly 1,000 frames in CPython and a stack of about 1 to 8 megabytes per thread in many native runtimes. Function calls also have a small call overhead, which compilers reduce by inlining short functions directly into the caller.

Languages also differ in how arguments are passed. The table summarizes the main strategies.

StrategyWhat the function receivesTypical languages
Pass by valueA copy of the valueC, Go, primitive types in Java
Pass by referenceAn alias to the caller’s variableC++ references, C# ref parameters
Pass by sharingA copy of a reference to the same objectPython, JavaScript, objects in Java
Pass by pointerAn address the function can dereferenceC, C++, Go
Argument passing strategies

Under pass by sharing, reassigning a parameter does not affect the caller, but mutating the shared object does, which surprises many beginners when a list changes after being passed to a function.

Kinds of functions

Modern languages offer several forms of functions, each suited to a different job. They differ mainly in whether they depend on outside state and whether they can be treated as values.

KindDefining propertyTypical use
Pure functionSame output for same input, no side effectsCalculations, easy testing and caching
Procedure or void functionPerforms an action, returns nothing usefulWriting files, printing, updating state
MethodBound to an object or classObject-oriented operations on data
Anonymous function or lambdaHas no name, defined inlineShort callbacks, sorting keys
ClosureCaptures variables from its enclosing scopeCallbacks that remember context
Higher-order functionTakes or returns other functionsmap, filter, decorators
Recursive functionCalls itselfTrees, divide-and-conquer algorithms
Common kinds of functions

Languages in which functions can be stored in variables, passed as arguments and returned from other functions are said to have first-class functions. JavaScript, Python and most modern languages support them, which enables functional programming styles.

A function is closely tied to other fundamentals, and precise usage helps when reading documentation and error messages.

  • Function versus mathematical function: a programming function may have side effects and depend on hidden state; only pure functions behave like functions in mathematics.
  • Function versus method: a method is a function associated with an object, receiving it implicitly as self or this.
  • Function versus loop: a loop repeats steps in one place, while a function packages steps for reuse in many places; recursion can replace a loop.
  • Return value versus exception: a function signals normal results with a return value and abnormal conditions with an exception.

Designing good functions and common mistakes

Well-designed functions do one thing, have a descriptive name, accept few parameters and avoid hidden side effects. Experienced programmers aim for functions that fit on one screen and keep parameter lists short, typically no more than three or four before grouping related values into an object.

MistakeConsequenceBetter practice
Doing several unrelated tasksHard to test and reuseSplit into focused functions
Modifying global stateUnexpected behavior elsewherePass values in and return results
Mutable default argument in PythonState leaks between callsDefault to None and create inside
Ignoring the return valueErrors or results silently lostCheck or use every meaningful result
Unbounded recursionStack overflowAdd a base case or use iteration
Common function design mistakes

Put simply

A function is a named set of instructions that a program can use again and again. You give it some information, it does its job and hands back a result.

It works like a coffee machine. You put in water and beans, press one button, and get coffee. You do not need to know every step inside; you only need to know what to put in and what comes out. The key takeaway is that functions let programmers write a task once and reuse it everywhere.

In practice

An online shop calculates shipping costs in six places: the product page, the cart, the checkout, order confirmation emails, the returns page and an internal reporting tool. Originally, each place contained its own copy of the calculation, and when the carrier changed its rates, two of the six copies were missed, so customers saw different prices on different pages.

A developer replaces all copies with one function, shipping_cost(weight_kg, country, express), which returns the price for a given weight, destination and speed. The function is pure, so it gets unit tests for every rate band. The next rate change requires editing one function and its tests, and every page shows the same correct price from the moment of deployment.