Conceptintro
Procedure and subroutine
Also called procedure, subroutine, void function, command.
A procedure, or subroutine, is a named piece of code that a program calls for an effect, such as output or a change of state, not for a result. Many languages write it as a function with no result.
- Applies to
- core-languages
Idea
A procedure is a named piece of code that a program calls to do something, not to compute a value. It can print a line, write a file, add an item to a list or change a variable. The call is a step of the program, and the program uses no result from it.
def add_item(cart, item):
cart.append(item)
print("added", item)
cart = []
add_item(cart, "pen")
add_item(cart, "book")
print(cart)
added pen
added book
['pen', 'book']
add_item has no return statement. The program calls it for its two effects: it changes the list, and it prints a line.
The words differ between languages. Wikipedia lists "function (also procedure, method, subroutine, routine, or subprogram)" as names for one idea1. Some languages use two words. Ada says: "There are two forms of subprogram: procedures and functions. A procedure call is a statement; a function call is an expression and returns a value."2 Other languages use one construct. Python calls a procedure "a function that returns no meaningful result; in Python, procedures return the value None"3.
How it works
- The definition. The definition of a procedure has a name, parameters and a body, as a Function has. It has no result type, or it has a special result type that means "no value", such as
voidor the unit type. - The call. The program writes the call as a statement on its own line. In Ada, "A procedure call is a statement"2. In C, Java or Go, a call is an expression, and an expression statement throws its value away.
- The effect. The body runs. The procedure does its work through effects: it changes data that the caller can see, such as a list that the caller passed, or it does input and output. Side effect describes these effects.
- The return. The body ends, or it runs a
returnstatement with no value. Control goes back to the statement after the call. Return value describes the return of a value.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A Kotlin function with no declared return type returns Unit, so it works as a procedure. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL has stored procedures, which CREATE PROCEDURE defines and CALL runs. Each database has its own languages for the body. No example file exists. |
| Bash | Native | |
| PowerShell | Native | A PowerShell function can write nothing to the output and only change state, so it works as a procedure. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no procedures. Scripts in a page use JavaScript. |
| CSS | Does not apply | CSS is a style sheet language. It declares styles and has no code that a program calls for an effect. |
| Regular expressions | Does not apply | A regular expression has no procedures. |
- Python. Python has only functions. A function with no
returnstatement, or with a barereturn, gives backNone, so a procedure is a function that returnsNone3. The interactive interpreter shows no output forNone, "so that procedure calls do not cause any output"3. - JavaScript. A function with no
returnstatement, or areturnwith no expression, gives backundefined. MDN says of the expression ofreturn: "If omitted, undefined is returned."4 - TypeScript. The result type
voidmarks a function that gives back no value. The TypeScript Handbook says that "void represents the return value of functions which don’t return a value"5. - Java. A method that gives back no value has the result type
void. The JLS says that the result of a method declaration "uses the keyword void to indicate that the method does not return a value"6. Areturnwith no value is allowed only in such a method: "It is a compile-time error if the return target of a return statement with no value is a method, and that method is not declared void."7 - C#. "Use void as the return type of a method or a local function to specify that the method doesn't return a value."8
- C. The return type of a function "must be a non-array object type or the type void"9. A
voidfunction can end withreturn;or by reaching the end of its body. - C++. C++ also uses
void. In areturnstatement, "The expression is optional in functions whose return type is (possibly cv-qualified) void"10. - Go. A Go function can have no result list. In a function without a result type, a
returnstatement "must not specify any result values"11. - Rust. A Rust function always gives back a value. "If the output type is not explicitly stated, it is the unit type"12. The unit type
()"has exactly one value (), and is used when there is no other meaningful value that could be returned"13. - Bash. A Bash function gives back only an exit status. "If return is supplied a numeric argument, that is the function’s return status; otherwise the function’s return status is the exit status of the last command executed before the return."14 A Bash function that only prints text or changes variables is a procedure in practice.
def greet(name):
print("Hello, " + name + "!")
greet("Ada")
result = greet("Alan")
print(result)
Hello, Ada!
Hello, Alan!
None
- Verdict: native. Python has no separate procedure keyword. A function with no
returnstatement is a procedure, and its call gives backNone.
#include <iostream>
#include <string>
void greet(const std::string& name) {
std::cout << "Hello, " << name << "!\n";
}
int main() {
greet("Ada");
greet("Alan");
}
Hello, Ada!
Hello, Alan!
- Verdict: native. A function with the return type
voidis a procedure.
public class Main {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Ada");
greet("Alan");
}
}
Hello, Ada!
Hello, Alan!
- Verdict: native. A method with the result type
voidis a procedure. The compiler rejects code that uses the result of its call.
#include <stdio.h>
static void greet(const char *name) {
printf("Hello, %s!\n", name);
}
int main(void) {
greet("Ada");
greet("Alan");
return 0;
}
Hello, Ada!
Hello, Alan!
- Verdict: native. A function with the return type
voidis a procedure. It ends at the end of its body or atreturn;.
using System;
class Program
{
static void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
static void Main()
{
Greet("Ada");
Greet("Alan");
}
}
Hello, Ada!
Hello, Alan!
- Verdict: native. A method with the return type
voidis a procedure.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Ada");
const result = greet("Alan");
console.log(result);
Hello, Ada!
Hello, Alan!
undefined
- Verdict: native. A function with no
returnstatement is a procedure, and its call gives backundefined.
function greet(name: string): void {
console.log("Hello, " + name + "!");
}
greet("Ada");
greet("Alan");
Hello, Ada!
Hello, Alan!
- Verdict: native. The result type
voidmarks a function that gives back no value.
package main
import "fmt"
func greet(name string) {
fmt.Println("Hello, " + name + "!")
}
func main() {
greet("Ada")
greet("Alan")
}
Hello, Ada!
Hello, Alan!
- Verdict: native. A function with no result list is a procedure. Its call can only be a statement.
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Ada");
let result = greet("Alan");
println!("{:?}", result);
}
Hello, Ada!
Hello, Alan!
()
- Verdict: native. A function with no output type returns the unit value
(), so a procedure is a function that returns unit.
greet() {
echo "Hello, $1!"
}
greet "Ada"
greet "Alan"
echo "status $?"
Hello, Ada!
Hello, Alan!
status 0
- Verdict: native. A Bash function gives back only an exit status, so a function that prints text or sets variables is a procedure.
Variations and related ideas
- Procedures and functions as two kinds. Pascal has separate procedure declarations and function declarations15. Ada has
procedureandfunction2. Wikipedia says that C, C++ and Rust "only use the term" function "irrespective of whether they return a value or not", and that ALGOL 60 and PL/I "only use the word procedure"1. - Void and unit. A language with types marks a procedure with a special type.
voidin C, C++, Java and C# means that there is no value. The unit type in Rust is a real type with one value, so a procedure is a function that returns that value. - Command query separation. Bertrand Meyer gave a design rule for methods. Martin Fowler describes it: "Queries: Return a result and do not change the observable state of the system (are free of side effects)." and "Commands: Change the state of a system but do not return a value."16 A command is a procedure.
- Methods. A procedure that belongs to a class is a method with no result, such as a
voidmethod in Java. See Method. - Output parameters. A procedure can give data back through its parameters, for example through a pointer in C or a
reforoutparameter in C#. See Parameter passing.
Pitfalls
Using the result of a procedure
A procedure in Python returns None. If a program stores the result of a procedure call in a variable, it loses the data that the variable held:
This code runs but gives a wrong answer on purpose.
def add_item(cart, item):
cart.append(item)
cart = ["pen"]
cart = add_item(cart, "book")
print(cart)
None
add_item changes the list and returns None3. The assignment then puts None in cart. Call the procedure as a statement: add_item(cart, "book").
A void function type in TypeScript can return a value
In TypeScript, void as the result of a function type does not stop a function from returning a value. The Handbook says: "Contextual typing with a return type of void does not force functions to not return something."5
This code runs but gives a wrong answer on purpose.
type Logger = () => void;
const log: Logger = () => true;
const result = log();
console.log(result);
true
The type checker accepts the arrow function, and at run time the call gives back true. Code must not use the result of a void function, because the type says nothing about it.
The status of the last command in Bash
A Bash function returns the exit status of its last command14. A procedure that ends with a test returns failure when the test is false, even when the procedure did its job:
This code runs but gives a wrong answer on purpose.
DEBUG=0
log_debug() {
[ "$DEBUG" = 1 ] && echo "debug: $1"
}
log_debug "start"
echo "status $?"
status 1
The test is false, so the && list fails, and the function returns 1. With set -e, or in an if, the caller treats this as an error. End the procedure with return 0, or use an if statement.
Cost
A procedure call costs the same as a function call: the arguments, the jump to the body and the jump back. No result value goes back.
The larger cost is in reasoning. A procedure does its work through effects, so its effects decide the order in which a program can call it. Fowler says of queries: "This is because you can use queries in many situations with much more confidence, introducing them anywhere, changing their order. You have to be more careful with modifiers."16
History
Subroutines came before the words function and procedure. On the EDSAC, David Wheeler developed a way to call a subroutine, the Wheeler Jump, "while working on the pioneering EDSAC machine in the 1950s"17. The EDSAC "lacked a suitable processor register or a hardware stack that might allow the return address to be easily stored"17, so the subroutine wrote the return address into its own last instruction.
The ALGOL 60 report used the word procedure for all subprograms: "A procedure declaration serves to define the procedure associated with a procedure identifier"18. Pascal and Ada split the idea into procedures and functions152. C used only functions and gave a procedure the return type void9, and Java, C# and C++ do the same.
Martin Fowler says that the term command query separation "was coined by Bertrand Meyer" in his book Object Oriented Software Construction16.
References
- Function (computer programming), Wikipedia, the introduction; Terminology
- Ada Reference Manual (Ada 2022), 6 Subprograms, paragraph 1
- Simple statements, The Python Language Reference, 7.1 Expression statements
- return, JavaScript reference, MDN Web Docs, Syntax
- More on Functions, The TypeScript Handbook, Other Types to Know About, void; Return type void
- Classes, The Java Language Specification, Java SE 25 Edition, 8.4.5 Method Result
- Blocks, Statements, and Patterns, The Java Language Specification, Java SE 25 Edition, 14.17 The return Statement
- void, C# reference, the introduction
- Function declarations, C reference, cppreference.com, Explanation
- return statement, C++ reference, cppreference.com, Explanation
- The Go Programming Language Specification, Return statements
- Functions, The Rust Reference, items.fn.implicit-return
- Primitive Type unit, The Rust Standard Library, the introduction
- Shell Functions, Bash Reference Manual, 3.3 Shell Functions
- ISO 7185 Pascal, 6.6.1 Procedure-declarations; 6.6.2 Function-declarations
- Command Query Separation, Martin Fowler, the whole page
- Wheeler Jump, Wikipedia, the introduction
- Revised Report on the Algorithmic Language Algol 60, 5.4 Procedure declarations
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XJRWGX Edit this page History Report an error Markdown