
Autor: 15.03.2024
What is the difference between a function and a procedure?
Function and procedure are two important concepts in programming. Some use them interchangeably, although there are significant differences between them in reality. We hope that after reading this article, you will understand what these differences are.
Returning Values
A function usually returns a value that can be used in further calculations or operations. On the other hand, a procedure does not return a value; it can only perform operations, manipulate data, etc.
Arguments
A function can take arguments (parameters) that are passed to the function to perform operations on them and return a result. Similarly, a procedure can also take arguments, but their passing is intended only for manipulation within the procedure, not necessarily returning any value.
Purity of Function
A pure function does not affect the state of variables outside its scope, and the result depends only on its arguments. This means that the function has no side effects. A procedure may change the state of variables outside its scope or have other side effects.
Examples
It will be best to illustrate these differences with a simple example.
Function
A function calculating factorial, a function calculating the distance between two points, etc.
Procedure
A procedure sorting a list, a procedure converting currency amounts, etc.
Functions, Procedures, and Programming Languages
Most popular programming languages, such as Python, C++, Java, allow the use of both functions and procedures. From a technical point of view, there are often no differences between them - the same language mechanisms are used.
The real differences lie in the application of appropriate conventions and approach to writing code. For example, in Python, you can use the keyword 'def' to define a code block that can be both a procedure and a function. If our function does not return a value, it will conceptually be closer to a procedure than a typical function. In modern functional code approaches , functions returning a value (pure functions) are much more commonly used. The concept of a procedure itself is considered outdated because it makes it difficult to understand and reuse code.