230
votes

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.

18
I think SICP gets this right. Functions exist only in math, and they represent what is knowledge. Procedures exist in programming languages (including functional ones), and they represent how to knowledge. Function: sqrt(x) = the y such that y^2=x. Procedure: (define (sqrt x) (newtons-method (lambda (y) (- (square y) x)) 1.0)).mk12
I'm taking a guess that SICP is an acronym for the book Structure and Interpretation of Computer Programs.jmrah

18 Answers

331
votes

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 commands which can be executed in order.

In most programming languages, even functions can have a set of commands. Hence the difference is only returning a value.

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.

43
votes

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.

22
votes

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.

12
votes

In general, a procedure is a sequence of instructions.
A function can be the same, but it usually returns a result.

11
votes

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.

7
votes

Basic Differences

  • A Function must return a value but in Stored Procedures it is optional: a procedure can return 0 or n values.
  • Functions can have only input parameters for it, whereas procedures can have input/output parameters.
  • For a Function it is mandatory to take one input parameter, but a Stored Procedure may take 0 to n input parameters.
  • Functions can be called from a Procedure whereas Procedures cannot be called from a Function.

Advanced Differences

  • Exceptions can be handled by try-catch blocks in a Procedure, whereas a try-catch block cannot be used in a Function.
  • We can go for Transaction Management in a Procedure, whereas in a Function we can't.

In SQL:

  • A Procedure allows SELECT as well as DML (INSERT, UPDATE, DELETE) statements in it, whereas Function allows only SELECT statement in it.
  • Procedures can not be utilized in a SELECT statement, whereas Functions can be embedded in a SELECT statement.
  • Stored Procedures cannot be used in SQL statements anywhere in a WHERE (or a HAVING or a SELECT) block, whereas Functions can.
  • Functions that return tables can be treated as another Rowset. This can be used in a JOIN block with other tables.
  • Inline Functions can be thought of as views that take parameters and can be used in JOIN blocks and other Rowset operations.
5
votes

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.

5
votes

This is a well-known old question, but I'd like to share some more insights about modern programming language research and design.

Basic answer

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:

  • As in RnRS, just marking the uninterested results as "unspecified" value (of unspecified type, if the language has to mention it) and it is sufficient to be ignored.
  • Specifying the uninterested result as the value of a dedicated unit type (e.g. Kernel's #inert) also works.
  • When that type is a further a bottom type, it can be (hopefully) statically verified and prevented used as a type of expression. The 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.

Further reading

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:

  • Functions in different branches of math are not always defined having same meanings. Functions in different programming paradigms may also be quite different (even sometimes the syntaxes of function call look similar). Sometimes the reasons to cause the differences are same, but sometimes they are not.
    • It is idiomatic to model computation by mathematical functions and then implement the underlying computation in programming languages. Be careful to avoid mapping them one to one unless you know what are being talked about.
  • Do not confuse the model with the entity be modeled.
    • The latter is only one of the implementation to the former. There can be more than one choices, depending on the contexts (the branches of math interested, for example).
    • In particular, it is more or less similarly absurd to treat "functions" as "mappings" or subsets of Cartesian products like to treat natural numbers as Von-Neumann encoding of ordinals (looking like a bunch of {{{}}, {}}...) besides some limited contexts.
  • Mathematically, functions can be partial or total. Different programming languages have different treatment here.
    • Some functional languages may honor totality of functions to guarantee the computation within the function calls always terminate in finite steps. However, this is essentially not Turing-complete, hence weaker computational expressiveness, and not much seen in general-purpose languages besides semantics of typechecking (which is expected to be total).
    • If the difference between the procedures and functions is significant, should there be "total procedures"? Hmm...
  • Constructs similar to functions in calculi used to model the general computation and the semantics of the programming languages (e.g. lambda abstractions in lambda calculi) can have different evaluation strategies on operands.
    • In traditional the reductions in pure calculi as well in as evaluations of expressions in pure functional languages, there are no side effects altering the results of the computations. As a result, operands are not required to be evaluated before the body of the functions-like constructs (because the invariant to define "same results" is kept by properties like β-equivalence guaranteed by Church-Rosser property).
    • However, many programming languages may have side effects during the evaluations of expressions. That means, strict evaluation strategies like applicative evaluation are not the same to non-strict evaluation ones like call-by-need. This is significant, because without the distinction, there is no need to distinguish function-like (i.e. used with arguments) macros from (traditional) functions. But depending on the flavor of theories, this still can be an artifact. That said, in a broader sense, functional-like macros (esp. hygienic ones) are mathematical functions with some unnecessary limitations (syntactic phases). Without the limitations, it might be sane to treat (first-class) function-like macros as procedures...
    • For readers interested in this topic, consider some modern abstractions.
  • Procedures are usually considered out of the scope of traditional math. However, in calculi modeling the computation and programming language semantics, as well as contemporary programming language designs, there can be quite a big family of related concepts sharing the "callable" nature. Some of them are used to implement/extend/replace procedures/functions. There are even more subtle distinctions.
4
votes

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.

3
votes

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.

3
votes

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

2
votes

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.

1
votes

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.

1
votes

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.

1
votes

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.");
    }
0
votes

In the context of db: Stored procedure is precompiled execution plan where as functions are not.

-3
votes

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.

-8
votes

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