1. What Is a Function?
A function is a code unit with an independent purpose that can be called and executed.
It usually accepts input parameters, performs specific operations, and returns a result as needed.
For example:
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
In this example:
add: function name.a,b: formal parameters (Parameters).10,20: actual arguments (Arguments).return: returns the execution result.result: the variable that receives the function's return value.
Logically, a function can be abstracted as:
where:
- f: the function itself.
- x: input.
- y: output.
However, functions in programming languages are not necessarily pure mathematical functions. They can modify external state, access files, send network requests, throw exceptions, or even return no meaningful value.
Therefore, a more accurate understanding of a function is: a program unit with a clear calling interface and execution logic.
2. Basic Components of a Function
A typical function usually includes a function declaration, a parameter list, a function body, and a return mechanism.
Take Python as an example:
def calculate_price(price, quantity):
total = price * quantity
return total
The meaning of each part is as follows:
| Component | Example | Purpose |
|---|---|---|
| Function definition keyword | def |
Declares a function |
| Function name | calculate_price |
Identifies the function |
| Parameter list | price, quantity |
Receives data provided by the caller |
| Function body | total = price * quantity |
Executes the specific logic |
| Return statement | return total |
Returns the result to the caller |
2.1 Function Definition and Function Call
Function definition and function call are two different concepts.
Function definition: describes what operations the function should perform.
Function call: actually triggers the function's execution.
def greet(name):
print("Hello,", name)
# Call the function
greet("Alice")
Defining a function itself usually does not immediately execute the function body; only when a call occurs does the program execute the function logic according to the language's rules.
The function call process can be abstracted as:
flowchart TD
A["Define function"] --> B["Call function"]
B --> C["Pass actual arguments"]
C --> D["Execute function body"]
D --> E["Produce return result"]
E --> F["Continue execution at call site"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that function calls are not always implemented through ordinary name-based calls. Object-oriented languages can call methods through objects, and functional languages can also pass function references through variables, closures, and higher-order functions.
2.2 Function Declaration and Function Definition
Different programming languages distinguish between function declaration and function definition in different ways.
Take the C language as an example:
// Function declaration
int add(int a, int b);
// Function definition
int add(int a, int b) {
return a + b;
}
A function declaration provides the compiler with interface information about the function, including its name, parameter types, and return type.
A function definition, in turn, provides the actual implementation of the function.
In C/C++, a function declaration can appear before the function definition, allowing the compiler to check whether calls are valid in advance.
However, languages such as Python, Java, and JavaScript generally use different declaration and definition mechanisms, so the conceptual distinction used in C cannot be applied directly.
III. Parameters and Parameter Passing
Parameters are the primary way a function exchanges data with outside code.
Two concepts usually need to be distinguished:
- Formal parameter (Parameter): the parameter variable declared in the function definition.
- Actual argument (Argument): the concrete value or expression passed in when the function is called.
For example:
def multiply(a, b):
return a * b
multiply(3, 5)
Here, a and b are formal parameters, and 3 and 5 are actual arguments.
3.1 Positional Arguments
Positional arguments are matched according to their position in the parameter list.
def introduce(name, age):
print(name, age)
introduce("Alice", 25)
Parameter correspondence:
| Formal parameter | Actual argument |
|---|---|
name |
"Alice" |
age |
25 |
A defining feature of positional arguments is that the order of the call must correspond to the order of the parameters in the function definition.
3.2 Keyword Arguments
Keyword arguments specify the corresponding value by parameter name.
def introduce(name, age):
print(name, age)
introduce(age=25, name="Alice")
Keyword arguments reduce the cognitive burden caused by parameter order.
JavaScript can achieve a similar calling style through object destructuring, object parameters, and similar techniques, but it does not have a native keyword argument mechanism identical to Python's.
3.3 Default Parameters
Default parameters allow certain parameters to be omitted when the function is called.
Python:
def greet(name, message="Hello"):
print(message, name)
greet("Alice")
greet("Bob", "Welcome")
Output:
Hello Alice
Welcome Bob
Default parameters are well suited to expressing configuration that has commonly used default values.
However, different languages implement default parameters with different rules.
For example:
- In Python, default parameter values are usually evaluated when the function definition is executed.
- In JavaScript, default parameter expressions are evaluated at call time, when the corresponding argument is missing or is
undefined. - C++ supports default arguments, and the default value is usually specified in the function declaration.
- Java does not support default parameters for ordinary methods; a similar effect is usually achieved through method overloading.
- Go does not support default parameter values for ordinary functions.
In Python, mutable default parameters require particular attention:
def append_item(item, items=[]):
items.append(item)
return items
print(append_item(1))
print(append_item(2))
Output:
[1]
[1, 2]
The reason is that the default list object is created only once, when the function is defined, and subsequent calls share the same object.
A safer way to write it:
def append_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
3.4 Variadic Parameters
Variadic parameters allow a function to receive a variable number of arguments.
Python:
def calculate_sum(*numbers):
return sum(numbers)
print(calculate_sum(1, 2, 3))
print(calculate_sum(1, 2, 3, 4, 5))
Here, *numbers collects any extra positional arguments into a tuple.
Variadic parameters in keyword form:
def print_info(**kwargs):
for key, value in kwargs.items():
print(key, value)
print_info(name="Alice", age=25)
Here, **kwargs collects any extra keyword arguments into a dictionary.
Other languages also have similar capabilities:
| Language | Variadic Parameter Mechanism |
|---|---|
| C | ... and stdarg.h |
| C++ | Variadic templates, ... |
| Java | Varargs, e.g. String... args |
| JavaScript | Rest parameters, e.g. ...args |
| Python | *args, **kwargs |
| Go | Variadic parameters, e.g. ...int |
| Rust | No traditional general-purpose variadic function mechanism; slices, collections, or macros are usually used |
Variadic parameters improve interface flexibility, but they can also reduce the clarity of parameter constraints, so they need to be used appropriately.
3.5 Parameter Passing Methods
Parameter passing determines how the caller's data is passed into a function and whether operations inside the function affect the data observable by the caller.
Common concepts include:
- Pass by value.
- Pass by reference.
- Pointer passing.
- Pass by sharing.
Among these, pass by value and pass by reference are especially easy to confuse.
Pass by Value
Pass by value means the function receives a copy of the argument value.
#include <stdio.h>
void change(int x) {
x = 100;
}
int main() {
int a = 10;
change(a);
printf("%d", a);
return 0;
}
Output:
10
Inside the function, the modification is made to the parameter copy, so the caller's variable is not modified directly.
Pointer Passing
In C, pointers allow a function to access the memory location of an object in the caller.
#include <stdio.h>
void change(int *x) {
*x = 100;
}
int main() {
int a = 10;
change(&a);
printf("%d", a);
return 0;
}
Output:
100
This is still pass by value: the function receives a copy of the pointer value, but the pointer points to the caller's variable, so the original object can be modified through dereferencing.
Pass by Reference
C++ supports reference parameters:
#include <iostream>
using namespace std;
void change(int &x) {
x = 100;
}
int main() {
int a = 10;
change(a);
cout << a;
return 0;
}
Output:
100
The function parameter x is a reference to a; modifying x means modifying a.
Parameter Passing in Java
Java has only pass by value; it does not have pass by reference in the traditional sense.
For primitive types, a copy of the primitive value is passed.
For objects, a copy of the object reference value is passed.
class User {
String name;
}
public class Main {
static void change(User user) {
user.name = "Bob";
}
public static void main(String[] args) {
User user = new User();
user.name = "Alice";
change(user);
System.out.println(user.name);
}
}
Output:
Bob
Because the parameter copy and the reference held by the caller's variable point to the same object, modifying the object's field affects the object state observed by the caller.
However, if the parameter is reassigned inside the function:
static void change(User user) {
user = new User();
user.name = "Bob";
}
The reference held by the caller is not rebound.
Parameter Passing in Python
Python typically uses a call-by-sharing model (also called object sharing).
The function receives the value of an object reference; the parameter name and the caller's variable name are independent of each other, but they may refer to the same object.
def modify(items):
items.append(100)
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
Output:
[1, 2, 3, 100]
If the parameter is rebound:
def modify(items):
items = [100, 200]
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
The output is still:
[1, 2, 3]
The reason is that rebinding items only changes the local name inside the function; it does not change the caller's numbers.
Therefore, when determining parameter-passing behavior, it is necessary to distinguish:
- Whether the object itself was modified.
- Whether the binding of the parameter variable was modified.
- Whether the caller and the function hold a reference to the same object.
4. Return Values
A return value is the mechanism by which a function provides a computation result or execution status to the caller.
For example:
def square(number):
return number * number
result = square(5)
print(result)
Output:
25
4.1 Functions With and Without Return Values
A function can return concrete data or can avoid explicitly returning data.
Python:
def get_name():
return "Alice"
def print_name():
print("Alice")
get_name() returns a string, while print_name() has no explicit return statement.
Note that different languages represent functions with no return value in different ways:
| Language | No return type |
|---|---|
| C | void |
| C++ | void |
| Java | void |
| JavaScript | Usually does not declare a return type; when no explicit return occurs, the result is undefined |
| Python | When no explicit return occurs, the result is None |
| Go | Does not declare a return type |
| Rust | Often uses () to represent the unit type |
4.2 Multiple Return Values
Some languages support functions returning multiple values.
Python:
def calculate(a, b):
return a + b, a - b
sum_result, diff_result = calculate(10, 5)
Python actually organizes multiple return results into a tuple, which the caller then unpacks.
Go supports explicit multiple return values:
package main
import "fmt"
func calculate(a, b int) (int, int) {
return a + b, a - b
}
func main() {
sum, diff := calculate(10, 5)
fmt.Println(sum, diff)
}
Java usually returns multiple related results through objects, record types, collections, or wrapper classes.
C usually achieves a similar effect through structs, pointer output parameters, and similar approaches.
4.3 Early Return
Early return means returning immediately when certain conditions are met during function execution.
def divide(a, b):
if b == 0:
return None
return a / b
Early return can:
- Reduce nesting levels.
- Handle invalid input early.
- Make the main logic clearer.
- Reduce unnecessary computation.
However, in scenarios such as resource management and transaction processing, you need to ensure that resources are properly released or rolled back when returning early.
5. Scope and Lifetime of Functions
Variables inside a function usually have their own scope and lifetime.
Understanding these two concepts helps avoid variable conflicts, accidental modification of external state, and resource management issues.
5.1 Local Variables
A local variable is a variable declared inside a function or local code block.
def calculate():
result = 100
return result
Here, result is a local variable inside the function and usually cannot be accessed directly from outside the function.
The visibility of a local variable is determined by the language's scoping rules.
5.2 Global Variables
A global variable is a variable declared in the global scope of a module or program.
count = 10
def show_count():
print(count)
show_count()
A function can read variables from an outer scope, but the rules for modifying them vary by language.
For example, Python:
count = 10
def update():
global count
count = 20
update()
print(count)
With the global declaration, a function can rebind a module-level variable.
In languages such as Java and C++, access to global or static state follows each language's own syntax and scoping mechanisms.
5.3 Lexical Scope
Lexical scope means that a variable's visibility is determined by the nesting structure of the code in the source program, not by where the function is actually called.
For example, JavaScript:
const name = "Global";
function outer() {
const name = "Outer";
function inner() {
console.log(name);
}
return inner;
}
const fn = outer();
fn();
Output:
Outer
inner is defined inside outer, so it can access the local variables in outer.
Even if inner is called after outer has finished executing, it can still access the relevant variables.
This leads to closures.
5.4 Closures
A closure is the structure formed by combining a function with the lexical environment it captures.
It lets a function access variables in an outer scope even after the outer function that defined it has finished executing.
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());
Output:
1
2
3
Execution process:
flowchart TD
A["Call createCounter"] --> B["Create local variable count = 0"]
B --> C["Create inner function"]
C --> D["Return inner function"]
D --> E["Outer function finishes executing"]
E --> F["Call the returned inner function"]
F --> G["Access and modify count"]
G --> H["Return the updated value"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Typical uses of closures:
- Encapsulating private state.
- Implementing counters.
- Implementing callback functions.
- Implementing function factories.
- Preserving the context of asynchronous operations.
- Implementing decorators and some functional programming patterns.
Note that a closure does not simply copy the outer variables. Depending on the specific implementation and semantic rules, the language runtime maintains the captured variables and their lifetime.
6. Functions and the Call Stack
A function call involves not only code execution but also the saving and restoring of runtime state.
In many languages and runtimes, function calls use a call stack to manage execution.
6.1 What Is the Call Stack?
The call stack is a stack-like structure used to manage the relationships between function calls and their execution state.
When a function is called, the runtime typically needs to save information related to the current call, such as:
- The return address.
- Parameters and local variables.
- Saved register information.
- Temporary computation state.
- The execution context between caller and callee.
This information is usually carried by a stack frame or a similar runtime structure.
Note that whether all of this data actually resides on the machine stack depends on compiler optimization, runtime implementation, and the target platform.
6.2 The Function Call Process
For example:
def first():
second()
def second():
third()
def third():
print("Hello")
first()
Function call relationships:
flowchart TD
A["Call first"] --> B["first calls second"]
B --> C["second calls third"]
C --> D["third executes output"]
D --> E["third returns"]
E --> F["second returns"]
F --> G["first returns"]
G --> H["main program continues execution"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The call stack follows the basic principle of last-in, first-out (LIFO).
If function A calls B, and B calls C, then C usually returns first, then B returns, and finally A returns.
6.3 Stack Frame
A stack frame is a runtime data structure used to hold execution state during a function call.
A typical stack frame may contain:
| Content | Purpose |
|---|---|
| Return address | Where to return after the function ends |
| Parameters | Data passed by the caller |
| Local variables | Local state inside the function |
| Saved registers | Register state that needs to be restored after the call |
| Temporary data | Intermediate computation results and other runtime information |
In actual compiled execution, some local variables may be kept in registers or optimized away, and are not necessarily all allocated on the stack.
6.4 Recursion and the Call Stack
Recursion is a programming technique in which a function calls itself directly or indirectly.
For example, computing a factorial:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Execution process:
flowchart TD
A["factorial(5)"] --> B["factorial(4)"]
B --> C["factorial(3)"]
C --> D["factorial(2)"]
D --> E["factorial(1)"]
E --> F["Return 1"]
F --> G["Return 2"]
G --> H["Return 6"]
H --> I["Return 24"]
I --> J["Return 120"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Recursion usually requires two key parts:
- Base Case: recursion stops once the condition is satisfied.
- Recursive Case: reduce the current problem to a smaller instance of the same kind.
Without an effective termination condition, recursion may continue indefinitely, eventually exhausting the call stack or hitting a runtime limit.
6.5 Stack Overflow
A stack overflow usually occurs when the space used by the call stack exceeds the limit allowed by the runtime or the system.
Common causes include:
- Recursion that goes too deep.
- Infinite recursion.
- Overly large local variables on the stack.
- An excessively deep chain of function calls.
For example:
def recursive():
recursive()
recursive()
This function has no termination condition, so the call depth keeps increasing until the recursion depth limit is finally triggered.
Note that Python usually prevents infinite recursion through the interpreter's recursion depth limit, and this does not necessarily manifest as a native thread stack overflow in the traditional sense.
7. What Is a Method?
A method usually refers to a function that is associated with a certain type, class, object, or specific context.
Functions and methods are very similar in execution capability, but they may differ in terms of ownership, invocation style, and receiver semantics.
For example, in Java:
class Calculator {
int add(int a, int b) {
return a + b;
}
}
Here, add is a method defined by the Calculator class.
When calling it, you usually need to go through an object:
Calculator calculator = new Calculator();
int result = calculator.add(10, 20);
An ordinary function, by contrast, can exist independently of any object:
def add(a, b):
return a + b
7.1 Differences Between Functions and Methods
| Comparison Dimension | Function | Method |
|---|---|---|
| Ownership | Can usually exist independently | Usually associated with a type, object, or context |
| Invocation style | Called directly or through a reference | Usually called through a receiver |
| Data access | Accesses data through parameters and the outer scope | Can access the receiver and its associated state |
| Typical use cases | Independent computation and general operations | Expressing the behavior of a certain type or object |
| State association | Not necessarily associated with object state | Often associated with object or type state |
Note that this is a common conceptual division; not all languages strictly distinguish functions from methods.
For example:
- Java mainly defines methods through classes and does not provide top-level ordinary functions independent of classes.
- Python supports both module-level functions and methods inside classes.
- In JavaScript, functions are first-class objects, and methods are usually functions invoked through object properties.
- Go uses ordinary functions and methods, declaring methods through a receiver.
- Rust uses functions and associated functions; methods are usually associated with an instance through a
selfparameter.
8. Common Types of Methods
Object-oriented languages usually classify methods into instance methods, static methods, class methods, and so on, based on the relationship between the method and the object or class.
8.1 Instance Method
An instance method is associated with a specific object instance and can usually access the object's instance state.
Java:
class User {
String name;
void introduce() {
System.out.println("Hello, " + name);
}
}
Invocation:
User user = new User();
user.name = "Alice";
user.introduce();
An instance method can access the member variables and other instance methods of the current object.
In Java, an instance method usually accesses the current object through an implicit this reference.
8.2 Static Method
A static method belongs to the class itself rather than to a specific instance.
Java:
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
Invocation:
int result = MathUtils.add(10, 20);
Static methods are typically used for:
- Utility class operations.
- Computations unrelated to instance state.
- Factory methods.
- General-purpose conversion logic.
A static method usually cannot directly access instance fields because it has no implicit current instance.
However, different languages do not define static members and their behavior in exactly the same way.
8.3 Class Method
A class method is a type of method found in languages such as Python, and it usually receives the class object as its first parameter.
class User:
count = 0
@classmethod
def get_count(cls):
return cls.count
Invocation:
print(User.get_count())
Here, cls represents the current class object.
Class methods can access class-level attributes and are also commonly used to implement alternative constructors.
8.4 Differences Between Static Methods and Class Methods
Python:
class Calculator:
factor = 2
@staticmethod
def add(a, b):
return a + b
@classmethod
def multiply(cls, a, b):
return (a + b) * cls.factor
Differences:
| Type | First implicit parameter | Can access instance state directly | Can access class state |
|---|---|---|---|
| Instance method | self |
Yes | Yes |
| Class method | cls |
Cannot directly access the state of a specific instance | Yes |
| Static method | None | Cannot access directly | Does not automatically receive the class object |
Note that it is not that a static method cannot access any object or class state. It simply does not automatically receive self or cls; if it obtains the relevant object through other parameters or the class name, it can still access it.
9. Method Receivers and the Binding Mechanism
An important difference between methods and ordinary functions is that a method call usually involves a receiver.
The receiver is the object or type that the current method is associated with.
9.1 this and self
Different languages use different ways to represent the current object.
| Language | Reference to the current instance |
|---|---|
| Java | this |
| C++ | this |
| JavaScript | this |
| Python | Usually self |
| Go | Explicitly declared receiver variable |
| Rust | self, &self, &mut self |
For example, in Python:
class User:
def __init__(self, name):
self.name = name
def introduce(self):
print(self.name)
self is an explicit parameter that represents the current instance.
Calling it:
user = User("Alice")
user.introduce()
Conceptually, this can be understood as:
User.introduce(user)
When an instance method is accessed in Python, the instance is bound to the method's first parameter.
9.2 Method Binding
Method binding means establishing an association between a method and a specific receiver, so that when the method is called it automatically obtains the corresponding object context.
Take JavaScript as an example:
const user = {
name: "Alice",
introduce() {
console.log(this.name);
}
};
user.introduce();
Here this points to user, the receiver object at the time the method is called.
But if the method is taken out on its own:
const fn = user.introduce;
fn();
At this point the form of the call has changed, and this no longer automatically points to user. In strict mode, this in an ordinary function call is undefined.
You can use bind() to fix the receiver: