Generally speaking, we all hear about the functions or procedures in programming languages. However, I just found out that I use these terms almost interchangeably (which is probably very wrong).
So, my question is:
What is the difference in terms of their functionality, their purpose and use?
An example would be appreciated.
This question is related to
function
terminology
procedure
This depends on the context.
In Pascal-like languages, functions and procedures are distinct entities, differing in whether they do or don't return a value. They behave differently wrt. the language syntax (eg. procedure calls form statements; you cannot use a procedure call inside an expression vs. function calls don't form statements, you must use them in other statements). Therefore, Pascal-bred programmers differentiate between those.
In C-like languages, and many other contemporary languages, this distinction is gone; in statically typed languages, procedures are just functions with a funny return type. This is probably why they are used interchangeably.
In functional languages, there is typically no such thing as a procedure - everything is a function.
I object with something I keep seeing over and over in most of these answers, that what makes a function a function is that it returns a value.
A function is not just any old method that returns a value. Not so: In order for a method to be a real function it must return the same value always given a specific input. An example of a method that is not a function is the random
method in most languages, because although it does return a value the value is not always the same.
A function therefore is more akin to a map (e.g. where x -> x'
for a one dimensional function). This is a very important distinction between regular methods and functions because when dealing with real functions the timing and the order in which they are evaluated should never matter where as this is not always the case with non functions.
Here's another example of a method that is not a function but will otherwise still return a value.
// The following is pseudo code:
g(x) = {
if (morning()) {
g = 2 * x;
}
else {
g = x;
}
return g;
}
I further object to the notion that procedures do not return values. A procedure is just a specific way of talking about a function or method. So that means if the underlying method that your procedure defines or implements returns a value then, guess what that procedure returns a value. Take for example the following snippet from the SICP:
// We can immediately translate this definition into a recursive procedure
// for computing Fibonacci numbers:
(define (fib n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (fib (- n 1))
(fib (- n 2))))))
Have you heard of recursive procedures much lately? They are talking about a recursive function (a real function) and it's returning a value and they are using the word "procedure". So what's the difference, then?
Well another way of thinking of a function (besides the meaning mentioned above) is as an abstract representation of an ideal like the numeral 1. A procedure is that actual implementation of that thing. I personally think they are interchangeable.
(Note, if you read that chapter from the link I provide you may find that a harder concept to grasp is not the difference between a function and a procedure, but a process and a procedure. Did you know that a recursive procedure can have an iterative process?)
An analog for procedures are recipes. For example; suppose you have a machine called make-pies
this machine takes in ingredients of (fruit, milk, flower, eggs, sugar, heat)
and this machine returns a pie
.
A representation of this machine might look like
make-pies (fruit, milk, flower, eggs, sugar, heat) = {
return (heat (add fruit (mix eggs flower milk)))
}
Of course that's not the only way to make a pie.
In this case we can see that:
A function is to a machine
as a procedure is to a recipe
as attributes are to ingredients
as output is to product
That analogy is OK but it breaks down when you take into account that when you are dealing with a computer program everything is an abstraction. So unlike in the case of a recipe to a machine we are comparing two things that are themselves abstractions; two things that might as well be the same thing. And I hold that they are (for all intent and purposes) the same thing.
In most contexts: a function returns a value, while a procedure doesn't. Both are pieces of code grouped together to do the same thing.
In functional programming context (where all functions return values), a function is an abstract object:
f(x)=(1+x)
g(x)=.5*(2+x/2)
Here, f is the same function as g, but is a different procedure.
There's a term subroutine or subprogram which stands for a parameterized piece of code that can be called from different places.
Functions and procedures are implementations of those. Usually functions return values and procedures don't return anything.
SELECT
as well as DML (INSERT
, UPDATE
, DELETE
) statements in it, whereas Function allows only SELECT
statement in it.SELECT
statement, whereas Functions can be embedded in a SELECT
statement.WHERE
(or a HAVING
or a SELECT
) block, whereas Functions can.JOIN
block with other tables.JOIN
blocks and other Rowset operations.In the context of db: Stored procedure is precompiled execution plan where as functions are not.
Function can be used within a sql statement whereas procedure cannot be used within a sql statement.
Insert, Update and Create statements cannot be included in function but a procedure can have these statements.
Procedure supports transactions but functions do not support transactions.
Function has to return one and only one value (another can be returned by OUT variable) but procedure returns as many data sets and return values.
Execution plans of both functions and procedures are cached, so the performance is same in both the cases.
Procedures and functions are both subroutines the only difference between them is that a procedure returns multiple (or at least can do) values whereas a function can only return one value (this is why function notation is used in maths as usually only one value is found at one given time) although some programming languages do not follow these rules this is their true definitions
More strictly, a function f obeys the property that f(x) = f(y) if x = y, i.e. it computes the same result each time it is called with the same argument (and thus it does not change the state of the system.)
Thus, rand() or print("Hello"), etc. are not functions but procedures. While sqrt(2.0) should be a function: there is no observable effect or state change no matter how often one calls it and it returns always 1.41 and some.
If we're language-agnostic here, procedure usually specifies a series of acts required to reliably and idempotently achieve certain result. That is, a procedure is basically an algorithm.
Functions, on the other hand, is a somewhat independent piece of code within a larger program. In other words, function is the implementation of a procedure.
In general, a procedure is a sequence of instructions.
A function can be the same, but it usually returns a result.
Inside procedure we can use DML (Insert /Update/Delete) statements, But Inside function we can not use DML statements.
Procedure can have both input\output parameters, But Function can have only input parameter.
We can use Try-Catch Block in Stored Procedure, But In Function We can not use Try-Catch block.
We can not use Stored Procedure in Select statement, But In Function We can use in Select statement.
Stored Procedure can return 0 or n values (max 1024), But Function can return only 1 value which is mandatory.
Stored Procedure can not be call from Function, But We can call function from Stored Procedure.
We can use transaction in Stored Procedure, But In function we can not use transaction.
We can not use Stored Procedure in Sql statement anywhere in the Where/Having/select section, But In function we can use.
We can not join Stored Procedure, But we can join function.
for more.. click here...http://dotnet-developers-cafe.blogspot.in/2013/08/difference-between-stored-procedure-and.html
In terms of ?#/Java, function is the block of code, which return particular value, but procedure is the block of code which return void (nothing). In C#/Java both functions and procedures more often called just methods.
//This is a function
public DateTime GetCurrentDate()
{
return DateTime.Now.Date;
}
//This is a procedure(always return void)
public void LogMessage()
{
Console.WriteLine("Just an example message.");
}
Example in C:
// function
int square( int n ) {
return n * n;
}
// procedure
void display( int n ) {
printf( "The value is %d", n );
}
Although you should note that the C Standard doesn't talk about procedures, only functions.
A function returns a value and a procedure just executes commands.
The name function comes from math. It is used to calculate a value based on input.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part.
But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.
This is a well-known old question, but I'd like to share some more insights about modern programming language research and design.
Traditionally (in the sense of structured programming) and informally, a procedure is a reusable structural construct to have "input" and to do something programmable. When something is needed to be done within a procedure, you can provide (actual) arguments to the procedure in a procedure call coded in the source code (usually in a kind of an expression), and the actions coded in the procedures body (provided in the definition of the procedure) will be executed with the substitution of the arguments into the (formal) parameters used in the body.
A function is more than a procedure because return values can also be specified as the "output" in the body. Function calls are more or less same to procedure calls, except that you can also use the result of the function call, syntactically (usually as a subexpression of some other expression).
Traditionally, procedure calls (rather than function calls) are used to indicate that no output must be interested, and there must be side effects to avoid the call being no-ops, hence emphasizing the imperative programming paradigm. Many traditional programming languages like Pascal provide both "procedures" and "functions" to distinguish this intentional difference of styles.
(To be clear, the "input" and "output" mentioned above are simplified notions based on the syntactic properties of functions. Many languages additionally support passing arguments to parameters by reference/sharing, to allow users transporting information encoded in arguments during the calls. Such parameter may even be just called as "in/out parameter". This feature is based on the nature of the objects being passed in the calls, which is orthogonal to the properties of the feature of procedure/function.)
However, if the result of a function call is not needed, it can be just (at least logically) ignored, and function definitions/function calls should be consistent to procedure definitions/procedure calls in this way. ALGOL-like languages like C, C++ and Java, all provide the feature of "function" in this fashion: by encoding the result type void
as a special case of functions looking like traditional procedures, there is no need to provide the feature of "procedures" separately. This prevents some bloat in the language design.
Since SICP is mentioned, it is also worth noting that in the Scheme language specified by RnRS, a procedure may or may not have to return the result of the computation. This is the union of the traditional "function" (returning the result) and "procedure" (returning nothing), essentially same to the "function" concept of many ALGOL-like languages (and actually sharing even more guarantees like applicative evaluations of the operands before the call). However, old-fashion differences still occur even in normative documents like SRFI-96.
I don't know much about the exact reasons behind the divergence, but as I have experienced, it seems that language designers will be happier without specification bloat nowadays. That is, "procedure" as a standalone feature is unnecessary. Techniques like void
type is already sufficient to mark the use where side effects should be emphasized. This is also more natural to users having experiences on C-like languages, which are popular more than a few decades. Moreover, it avoids the embarrassment in cases like RnRS where "procedures" are actually "functions" in the broader sense.
In theory, a function can be specified with a specified unit type as the type of the function call result to indicate that result is special. This distinguishes the traditional procedures (where the result of a call is uninterested) from others. There are different styles in the design of a language:
#inert
) also works.void
type in ALGOL-like languages is exactly an example of this technique. ISO C11's _Noreturn
is a similar but more subtle one in this kind.As the traditional concept derived from math, there are tons of black magic most people do not bother to know. Strictly speaking, you won't be likely get the whole things clear as per your math books. CS books might not provide much help, either.
With concerning of programming languages, there are several caveats:
{{{}}, {}}
...) besides some limited contexts.Procedures: 1.Procedures are the collections of statements that defines parameterized computations. 2.Procedures cannot return values.
3.Procedures cannot be called from function.
Functions 1.Functions structurally resemble procedures but are semantically modeled on mathematical functions. 2.It can return values 3.Function can be called from procedures.
Source: Stackoverflow.com