Back to series
· 10 min read

Function Definition & Invocation


I. What Is a Function?

A function is a block of program code that performs an independent task and can be called repeatedly.

It encapsulates a set of related operations and provides programs with modular execution capabilities through explicit input and output interfaces.

For example:

def add(a, b):
    return a + b

result = add(10, 20)
print(result)

Here, an add function is defined to calculate the sum of two numbers.

Functions have the following basic characteristics:

  • Encapsulation: Organizes a set of operations into an independent logical unit.
  • Reusability: The same function can be called repeatedly in different places.
  • Parameterization: Receives different inputs through parameters.
  • Return value: Provides calculation results to the caller through a return mechanism.
  • Abstraction: The caller does not need to understand the specific internal implementation of the function.

Functions are not only a tool for code reuse but also an important foundation for program control flow, module boundaries, and software architecture.

II. Basic Components of a Function

A typical function usually consists of a function name, a parameter list, a function body, and a return value.

def calculate_area(width, height):
    area = width * height
    return area

Meaning of each part:

Component Example Purpose
Function definition keyword def Declares a function
Function name calculate_area Identifies the function
Parameter list width, height Receives data passed in by the caller
Function body area = width * height Executes the actual logic
Return statement return area Returns the result to the caller

The syntax for defining functions differs among programming languages, but the core structure is basically the same.

1. Python Function Definition

def add(a, b):
    return a + b

2. Java Function Definition

In Java, functions are usually called methods (Method), and methods must be defined within type structures such as classes or interfaces.

public class Calculator {

    public int add(int a, int b) {
        return a + b;
    }
}

3. JavaScript Function Definition

function add(a, b) {
    return a + b;
}

JavaScript also supports function expressions and arrow functions:

const add = function(a, b) {
    return a + b;
};

const multiply = (a, b) => a * b;

4. C Language Function Definition

int add(int a, int b) {
    return a + b;
}

C functions require explicit return types and parameter types.

III. Function Definition and Function Calls

Function definition and function calling are two different concepts.

  • Function definition: Declares the function's name, parameters, return type, and concrete implementation.
  • Function call: Triggers execution of the function body through the function name or a function reference.

1. Function Definition

def greet(name):
    print("Hello,", name)

When the function definition statement is executed, Python creates the corresponding function object and binds it to the name greet.

At this point, the code in the function body has usually not yet been executed.

2. Function Call

greet("Alice")

The program executes the function body only after the function is called.

3. Execution Relationship Between Definition and Invocation

flowchart TB
    A["Write a function definition"] --> B["Create or declare a function"]
    B --> C["Program execution reaches the call site"]
    C --> D["Prepare arguments"]
    D --> E["Enter function execution"]
    E --> F["Execute function body"]
    F --> G["Return result or finish execution"]
    G --> H["Caller continues execution"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note that when a function definition is executed depends on the language.

For example:

  • Python creates a function object when it executes the def statement.
  • JavaScript handles function declarations and function expressions according to the declaration type and execution context.
  • C and Java usually complete the relevant processing of functions or methods at compile time, and execute call instructions at runtime.

Therefore, function definitions in all languages cannot be understood as creating functions only at runtime.

IV. Parameters and Arguments

Parameters are the interface through which a function receives external data.

When defining and calling functions, it is necessary to distinguish formal parameters (Parameter) from actual arguments (Argument).

1. Formal Parameters (Parameter)

Formal parameters are variables declared in a function definition.

def add(a, b):
    return a + b

Here, a and b are formal parameters.

They describe what data the function needs to receive.

2. Actual Arguments (Argument)

Actual arguments are the concrete values or expressions passed when calling a function.

result = add(10, 20)

Here, 10 and 20 are actual arguments.

3. Differences Between Formal Parameters and Actual Arguments

Comparison Dimension Formal Parameter Actual Argument
English Parameter Argument
Where it appears Function definition Function call
Nature Parameter variable Passed-in data or expression
Role Describes the function's input interface Provides concrete input

4. Parameter Passing Process

flowchart TB
    A["Caller prepares actual arguments"] --> B["Execute function call"]
    B --> C["Bind or pass arguments according to language rules"]
    C --> D["Function receives corresponding parameters"]
    D --> E["Use parameters to execute function body"]
    E --> F["Produce computation result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Parameter binding and low-level parameter passing are not concepts at the same level.

Parameter binding belongs to language semantics and determines how arguments correspond to formal parameters; low-level parameter passing is determined by the compiler, runtime, and ABI, and may use registers, the stack, or other mechanisms.

V. Common Forms of Function Parameters

Different languages provide various parameter forms to meet different function call requirements.

1. Positional Arguments

They are matched according to their position in the definition.

def introduce(name, age):
    print(name, age)

introduce("Alice", 25)

Correspondence:

  • "Alice" corresponds to name.
  • 25 corresponds to age.

Positional arguments require the order of the call to match the order in which the parameters are defined.

2. Keyword Arguments

Values are passed by specifying the parameter name.

def introduce(name, age):
    print(name, age)

introduce(age=25, name="Alice")

Keyword arguments do not depend on positional order, but they must comply with the parameter binding rules defined by the language.

In Python, positional and keyword arguments can be combined:

introduce("Alice", age=25)

3. Default Arguments

A default value is specified for a parameter when the function is defined.

def greet(name, message="Hello"):
    print(message, name)

greet("Alice")
greet("Bob", "Welcome")

Output:

Hello Alice
Welcome Bob

When the caller does not provide message, the function uses the default value.

Common pitfalls with Python default arguments:

Default argument expressions are usually evaluated when the function is defined, not re-evaluated on every call.

For example:

def append_item(item, items=[]):
    items.append(item)
    return items

print(append_item(1))
print(append_item(2))

Result:

[1]
[1, 2]

The reason is that the default list object is shared across multiple calls.

A safer way to write it:

def append_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

4. Variadic Arguments

When a function needs to accept an unfixed number of arguments, variadic parameters can be used.

Python:

def add_all(*numbers):
    return sum(numbers)

print(add_all(1, 2, 3))
print(add_all(1, 2, 3, 4, 5))

*numbers collects positional arguments into a tuple.

Python also supports **kwargs, which is used to collect keyword arguments:

def show_info(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

show_info(name="Alice", age=25)

kwargs is collected into a dictionary.

5. Comparison of Parameter Forms

Parameter Type Purpose Python Example
Positional argument Matched by position func(10, 20)
Keyword argument Matched by name func(a=10)
Default argument Provides a default value def func(a=10)
Variadic positional argument Accepts multiple positional arguments *args
Variadic keyword argument Accepts multiple keyword arguments **kwargs

Parameter mechanisms are not entirely the same across languages. For example, Java uses overloading and varargs, while C uses fixed parameter lists or a specific variadic mechanism.

6. Pass by Value and Pass by Reference

Parameter passing is a concept that is very easily confused in function design.

Common terms include:

  • Pass by value.
  • Pass by reference.

To understand these two concepts, you need to focus on what exactly is shared between the caller and the callee when a function is called.

1. Pass by Value

Pass by value means the function receives a copy of the argument's value.

Modifying the parameter variable inside the function does not directly change the caller's original variable.

C example:

#include <stdio.h>

void change(int x) {
    x = 100;
}

int main() {
    int a = 10;

    change(a);

    printf("%d\n", a);
    return 0;
}

Output:

10

Reason:

  • The value of a is 10.
  • When change(a) is called, the value is copied to parameter x.
  • Modifying x does not affect a.

2. Pass by Reference

Pass by reference means the function parameter directly references the variable provided by the caller.

In languages that support reference parameters, a function can modify the caller's variable through the parameter.

C++ example:

#include <iostream>
using namespace std;

void change(int& x) {
    x = 100;
}

int main() {
    int a = 10;

    change(a);

    cout << a << endl;
}

Output:

100

Here, int& x is a reference parameter, and x and the caller's variable a refer to the same object.

3. Differences Between Pointer Passing and Reference Passing

C has no native syntax for reference parameters, but pointers can be used to indirectly modify the caller's data.

void change(int *x) {
    *x = 100;
}

int main() {
    int a = 10;

    change(&a);
}

This is still pass by value: what is passed is a copy of the pointer value.

However, the pointer copy and the original pointer point to the same block of memory, so the original variable can be modified through dereferencing.

This shows that:

Pass by value does not necessarily mean the caller's data cannot be modified; the key is whether the passed value provides access to a shared object.

4. Python's Parameter Passing Mechanism

Python is usually described as object reference passing (Call by Sharing), also called pass-by-object-sharing.

When a function is called, the parameter name is bound to the passed object.

def change(items):
    items.append(100)

data = [1, 2, 3]

change(data)

print(data)

Output:

[1, 2, 3, 100]

The function accesses the same list object through the parameter, so the list contents change.

But if the parameter is rebound:

def change(items):
    items = [100, 200]

data = [1, 2, 3]

change(data)

print(data)

The output is still:

[1, 2, 3]

The reason is that inside the function, the local name items is merely made to refer to another list; the binding of the caller's name data is not changed.

5. Parameter Passing Mechanisms in Different Languages

Language Common Parameter Passing Mechanism
C Pass by value, including pointer values
C++ Pass by value, reference parameters
Java Pass by value, including object reference values
Python Pass-by-object-sharing
JavaScript Pass by value, including object reference values
Go Pass by value, including pointer values
Rust Pass by value, borrowing and mutable borrowing

In particular, note that:

Java does not support pass by reference in the traditional sense. Object parameters pass a copy of the object reference value, so the object's contents can be modified, but the caller's reference variable cannot be changed by reassigning the parameter.

VII. Function Return Values (Return Value)

A return value is the mechanism by which a function outputs a computed result to the caller.

Through language constructs such as return, the current function execution can be ended and the result handed back to the caller.

1. Returning a Single Value

def multiply(a, b):
    return a * b

result = multiply(3, 4)
print(result)

Return result:

12

2. Functions Without a Return Value

Some functions are only responsible for performing an operation and do not need to return a meaningful result.

Python:

def log_message(message):
    print(message)

Java:

public void logMessage(String message) {
    System.out.println(message);
}

C:

void log_message(const char *message) {
    printf("%s\n", message);
}

Different languages express functions without a return value in different ways.

If a Python function does not explicitly execute return, it implicitly returns None.

3. Returning multiple values

Python supports returning multiple results via a tuple:

def calculate(a, b):
    return a + b, a - b

sum_value, diff_value = calculate(10, 5)

In essence, the function returns a single tuple, and the values are obtained by unpacking it.

Other languages can achieve similar functionality using structs, objects, tuples, or multiple output parameters.

4. Execution characteristics of return

return generally serves two purposes:

  1. Ending the execution of the current function.
  2. Handing the return result back to the caller.

For example:

def check_number(n):
    if n < 0:
        return "negative"

    return "non-negative"

Once the condition holds and the first return is executed, the current function will not continue executing the statements after it.

5. The function return process

flowchart TB
    A["Caller executes the function call"] --> B["Enter the function body"]
    B --> C["Execute the computation logic"]
    C --> D{"Is a return statement executed?"}
    D -->|"Yes"| E["Prepare the return value"]
    D -->|"No"| F["Execute the remaining function logic"]
    F --> D
    E --> G["End the current function"]
    G --> H["Return to the caller"]
    H --> I["Receive or process the return value"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

VIII. The underlying execution mechanism of function calls

A function call is not merely a syntactic operation at the source-code level; ultimately, the actual execution must be carried out by the compiler, the runtime, and the CPU.

A typical function call involves:

  • Preparing arguments.
  • Passing arguments.
  • Saving the return address.
  • Establishing a stack frame.
  • Executing the function body.
  • Preparing the return value.
  • Restoring the stack frame.
  • Returning control flow.

1. Function calls and the call stack

The call stack is an important data structure used at runtime to manage the relationships between function calls.

When a function calls another function, it usually needs to save the execution state of the current function and establish a corresponding execution environment for the called function.

For example:

def first():
    second()

def second():
    third()

def third():
    print("Hello")

first()

Function call relationships:

flowchart TB
    A["first()"] --> B["second()"]
    B --> C["third()"]
    C --> D["print()"]
    D --> E["Return to third()"]
    E --> F["Return to second()"]
    F --> G["Return to first()"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The call stack follows the last-in, first-out (LIFO) principle.

When a function is called, a new call context is established; when the function returns, the current call context is destroyed or exited.

2. Stack Frame

Every function call is usually associated with a stack frame.

A stack frame is used to store some of the state information required for function execution.

Common contents include:

  • The return address.
  • Local variables.
  • Parameters or parameter-related information.
  • Saved registers.
  • Temporary computation data.
  • Stack alignment padding space.

A typical stack frame can be abstractly represented as:

High address
┌────────────────────────┐
│ Caller stack frame     │
├────────────────────────┤
│ Return address         │
├────────────────────────┤
│ Saved registers        │
├────────────────────────┤
│ Local variables        │
├────────────────────────┤
│ Temporary space        │
└────────────────────────┘
Low address

This is only a conceptual layout.

The actual layout depends on the CPU architecture, ABI, compiler optimizations, and runtime implementation.

For example:

  • Parameters may be passed through registers.
  • Local variables may be allocated directly in registers.
  • The compiler may omit the frame pointer.
  • Inlining optimizations may eliminate the actual function call.

3. The machine-level process of a function call

Taking x86-64 as an example, an ordinary function call usually involves the call and ret instructions.

  • call: saves the return address and transfers control flow to the target function.
  • ret: restores the return address from the stack and transfers control back to the caller.

Conceptual process:

flowchart TB
    A["Execute call instruction"] --> B["Save return address"]
    B --> C["Jump to target function"]
    C --> D["Execute function logic"]
    D --> E["Prepare return value"]
    E --> F["Execute return instruction ret"]
    F --> G["Restore return address"]
    G --> H["Continue executing caller code"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note that call and ret are specific mechanisms in the x86 instruction set; not all CPU architectures use the same function call instructions.