Programming Search⌘K

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)
Output
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

  1. 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 void or the unit type.
  2. 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.
  3. 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.
  4. The return. The body ends, or it runs a return statement with no value. Control goes back to the statement after the call. Return value describes the return of a value.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeA Kotlin function with no declared return type returns Unit, so it works as a procedure. No example file exists because kotlinc is not installed.
SQLNativeSQL has stored procedures, which CREATE PROCEDURE defines and CALL runs. Each database has its own languages for the body. No example file exists.
BashNative
PowerShellNativeA 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.
HTMLDoes not applyHTML is a markup language and has no procedures. Scripts in a page use JavaScript.
CSSDoes not applyCSS is a style sheet language. It declares styles and has no code that a program calls for an effect.
Regular expressionsDoes not applyA regular expression has no procedures.
  • Python. Python has only functions. A function with no return statement, or with a bare return, gives back None, so a procedure is a function that returns None3. The interactive interpreter shows no output for None, "so that procedure calls do not cause any output"3.
  • JavaScript. A function with no return statement, or a return with no expression, gives back undefined. MDN says of the expression of return: "If omitted, undefined is returned."4
  • TypeScript. The result type void marks 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. A return with 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 void function can end with return; or by reaching the end of its body.
  • C++. C++ also uses void. In a return statement, "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 return statement "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.
PythonGitHub
def greet(name):
    print("Hello, " + name + "!")


greet("Ada")
result = greet("Alan")
print(result)
Output
Hello, Ada!
Hello, Alan!
None
  • Verdict: native. Python has no separate procedure keyword. A function with no return statement is a procedure, and its call gives back None.
#include <iostream>
#include <string>

void greet(const std::string& name) {
    std::cout << "Hello, " << name << "!\n";
}

int main() {
    greet("Ada");
    greet("Alan");
}
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. A function with the return type void is a procedure.
JavaGitHub
public class Main {
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        greet("Ada");
        greet("Alan");
    }
}
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. A method with the result type void is 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;
}
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. A function with the return type void is a procedure. It ends at the end of its body or at return;.
using System;

class Program
{
    static void Greet(string name)
    {
        Console.WriteLine("Hello, " + name + "!");
    }

    static void Main()
    {
        Greet("Ada");
        Greet("Alan");
    }
}
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. A method with the return type void is a procedure.
JavaScriptGitHub
function greet(name) {
  console.log("Hello, " + name + "!");
}

greet("Ada");
const result = greet("Alan");
console.log(result);
Output
Hello, Ada!
Hello, Alan!
undefined
  • Verdict: native. A function with no return statement is a procedure, and its call gives back undefined.
TypeScriptGitHub
function greet(name: string): void {
  console.log("Hello, " + name + "!");
}

greet("Ada");
greet("Alan");
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. The result type void marks 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")
}
Output
Hello, Ada!
Hello, Alan!
  • Verdict: native. A function with no result list is a procedure. Its call can only be a statement.
RustGitHub
fn greet(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    greet("Ada");
    let result = greet("Alan");
    println!("{:?}", result);
}
Output
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.
BashGitHub
greet() {
  echo "Hello, $1!"
}

greet "Ada"
greet "Alan"
echo "status $?"
Output
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.
  • Procedures and functions as two kinds. Pascal has separate procedure declarations and function declarations15. Ada has procedure and function2. 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. void in 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 void method in Java. See Method.
  • Output parameters. A procedure can give data back through its parameters, for example through a pointer in C or a ref or out parameter 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)
Output
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);
Output
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 $?"
Output
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

  1. Function (computer programming), Wikipedia, the introduction; Terminology
  2. Ada Reference Manual (Ada 2022), 6 Subprograms, paragraph 1
  3. Simple statements, The Python Language Reference, 7.1 Expression statements
  4. return, JavaScript reference, MDN Web Docs, Syntax
  5. More on Functions, The TypeScript Handbook, Other Types to Know About, void; Return type void
  6. Classes, The Java Language Specification, Java SE 25 Edition, 8.4.5 Method Result
  7. Blocks, Statements, and Patterns, The Java Language Specification, Java SE 25 Edition, 14.17 The return Statement
  8. void, C# reference, the introduction
  9. Function declarations, C reference, cppreference.com, Explanation
  10. return statement, C++ reference, cppreference.com, Explanation
  11. The Go Programming Language Specification, Return statements
  12. Functions, The Rust Reference, items.fn.implicit-return
  13. Primitive Type unit, The Rust Standard Library, the introduction
  14. Shell Functions, Bash Reference Manual, 3.3 Shell Functions
  15. ISO 7185 Pascal, 6.6.1 Procedure-declarations; 6.6.2 Function-declarations
  16. Command Query Separation, Martin Fowler, the whole page
  17. Wheeler Jump, Wikipedia, the introduction
  18. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/XJRWGX/text.yaml