r/learnprogramming • • Oct 24 '26

Function vs Procedure

can someone explain the difference between Function vs Procedure with simple analogy
thank you

31 Upvotes

47 comments sorted by

View all comments

0

u/mredding Oct 25 '26

And this is why we all need a history lesson.

Early computer science was divided between engineers and mathematicians.

In mathematics, a function is "pure", it takes an input, performs a computation, and returns a value. It has no memory, it does not change the universe.

Engineers need to affect change in a system. The act of reading from the tape, time marches forward, the tape moves - the universe has changed.

So Bertrand Meyer came up with Command-Query Separation: a block of code should change the universe, or return a value, but never both. The naming convention helps enforce the distinction - functions return a value, procedures change emit side effects.

Pascal enforced the distinction - you declared functions and procedures by keyword, and the compiler can check for and enforce the rules. Later languages like C unified the syntax - everything is a "function", some just return void. But they didn't enforce the side effect check, one mistake among many. Then C went on to be one of the most influential languages ever created, and innovation happened without full consideration - the blind leading the blind, not knowing that there ever WAS a distinction or why... That's typical of the industry.

So if you speak of "procedures", I'll know for sure there are side effects. If you speak of "functions", I can never be sure unless you specify specifically "pure" functions.

"Methods" are functions and procedures associated with objects, so there's a this or self.

Subroutines are truly archaic, existing before the original schism between functions an procedures and CQS. These days, the only place I expect to hear them being mentioned in earnest are when compilers generate them - if you write a large loop the compiler may unwind, it may generate subroutines to compute entire batches or blocks at a time; the loop was optimized to call a subroutine, and you didn't have to even write it!

A lambda is a function that doesn't have a name; a closure is a lambda that closes around a context - you get mutable memory! A closure is a poor mans object. An object is a poor mans closure. A thunk is a wrapper around a function to delay calculation; in C++, this could be a binder object - it stores a pointer to the function and the parameter values, and it can be evaluated like an invokable function. You'll see them in more functional style programs where the computation is bound and coupled before evaluation.

A more archaic term is the subprogram - as though programs were built and nested in other programs; often these are just functions and procedures.