Can someone explain the difference between a function and a procedure with a simple analogy?
What's the difference between a function and a procedure?
Answers
Think of a function as a calculator: you give it numbers and it gives a result back. A procedure is more like a set of instructions for turning on a light: the point is to do something, not hand you a value.
That's the traditional distinction. In practice, the terminology depends on the language, and a function can also do things besides returning a value.
Reply to this answer
Check the language you're learning before treating this as a hard rule. Some languages distinguish functions from procedures, while others use function for both kinds of routine.
For example, a Python function without an explicit return value returns None. A Java method declared void doesn't return a value. Both can still perform actions.
Reply to this answer
There's also a mathematical meaning of function: a relationship that maps inputs to outputs. In programming, people sometimes use function more loosely for a block of code that can return a value and also change things elsewhere.
A pure function is the narrower idea. Given the same inputs, it produces the same output without side effects. Not every programming function is pure.
Reply to this answer
Database terminology can make the simple rule a little messy. Stored functions and stored procedures are called differently, and a stored procedure can produce a result set even though it is called a procedure. The exact behavior depends on the SQL system.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions