261

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.

3
  • See also: stackoverflow.com/q/10388393/974555
    – gerrit
    Jan 29, 2013 at 22:28
  • 6
    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
    May 28, 2014 at 19:47
  • 3
    I'm taking a guess that SICP is an acronym for the book Structure and Interpretation of Computer Programs.
    – jmrah
    Jun 22, 2021 at 16:28

18 Answers 18

370

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.

12
  • How can you assure no side effects either in an imperative (java, c) or declarative language (scala, scheme)?
    – orlybg
    Oct 10, 2013 at 18:05
  • 3
    @orlybg, in declarative languages, the consistency comes from the implementation of the language. Their scope restrictions prevent them from having side effects. On the other hand, imperative languages exploit their side effects explicitly. Side effects are not always bad. Oct 28, 2013 at 4:37
  • I'm reading the following Ada tutorial (goanna.cs.rmit.edu.au/~dale/ada/aln/8_subprograms.html), where the second paragraph of that page starts with "Procedures in Ada are similar to those in Pascal. A procedure can contain return statements.". Is this an error in the text? Or does it mean that it can have return statements but don't return any values?
    – jviotti
    Jan 14, 2015 at 23:24
  • 3
    In pascal, procedures do not have return statements, only functions do. Must be an error in the text. However, a procedure can have an "exit" statement, which could act as a "return" statement without arguments, meaning no return values. Mar 2, 2016 at 20:11
  • function can get inputs and return just only an output. procedure or macro can get inputs and not return any data only execute number of statements. main difference is procedure cant return any data type.
    – EsmaeelE
    Jul 8, 2017 at 2:13
52

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.

1
  • 2
    and documentation of programming languages can call functions and procedures whatever it likes, because people will accept any name since the background behind those names has been washed out long ago. May 11, 2015 at 9:25
27

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.

2
  • 6
    ...the C Standard doesn't talk about procedures, only functions. That's because it only has functions. A function that returns nothing is a void function. Kernighan & Ritchie Ch 1.7: "In C, a function is equivalent to a subroutine or function in Fortran, or a procedure or function in Pascal." In other words... this answer is wrong.
    – Mogsdad
    Aug 12, 2015 at 15:41
  • 13
    The answer is not wrong, and it is a good example of the difference between pure functions and procedures. K&R called every subroutine a "function" to keep things simple, but a subroutine with side effects is in fact a "procedure", not a "function" in the canonical sense from mathematics. C might be a better language if it distinguished real functions from procedures, this would help with static analysis, performance optimization, and parallelization. Sep 18, 2015 at 2:59
14

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

12

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.

10

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.
1
  • 6
    This answer is very language-specific, while the question was language-agnostic. The statements here are not all true in the general case, but it would be helpful if you clarified the language or environment you're asserting them for.
    – Mogsdad
    Aug 12, 2015 at 15:25
10

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.
1
  • Very good theoretical answer. A lot more information (too much more?) than the OP wanted, because it covers subroutines, coroutines, continuations, partial and total functions, and exceptions. Keep it simple and smart. Oct 10, 2022 at 18:06
6

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.

2
  • 3
    This usage is relavent in the context of "functional" programming. Be aware that many (often imperative) languages which call their subprograms "functions" do not require this property. Apr 6, 2009 at 14:29
  • 2
    I didn't suggest that programming languages require this property. Anyway, one can write strict functions in any language, and I feel it is good habit to program as much as possible in clean functions, then glue the pieces together with some main procedure.
    – Ingo
    Apr 6, 2009 at 14:43
4

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

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

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
  • 2
    This answer is very language-specific, while the question was language-agnostic. The statements here are not all true in the general case, but it would be helpful if you clarified the language or environment you're asserting them for.
    – Mogsdad
    Aug 12, 2015 at 15:25
  • This answer is completely incorrect for the vast majority of programming languages. Procedures only have input parameters, and functions have both input and output.
    – AStopher
    Jan 28, 2016 at 10:17
2

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.

2

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.

0
1

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.

3
  • 2
    A function that always returns the same value for given arguments is sometimes called a "pure function". In most languages that distinguish between procedures and functions, functions are not required to be pure, and the term "function" is correctly used to refer to subroutines that can have side effects and that can return different results on successive calls with the same arguments. (And in C-like languages, even subroutines that don't return values are properly called "functions".) May 15, 2014 at 15:59
  • Agreed, which is why I end bay saying the the words are interchangeable.
    – dkinzer
    May 15, 2014 at 19:56
  • 1
    Yes, but you begin by saying that "A function is not just any old method that returns a value", whereas in many languages that's exactly what a function is. May 15, 2014 at 20:37
1

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

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

-3

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.

3
  • 3.Procedures cannot be called from function. In what language is this true? None that I have experience in have this restriction.
    – Mogsdad
    Aug 12, 2015 at 15:17
  • It is true. If you call a procedure from a function, then it is not a function. As to what language enforces this, that is a good question, to which I do not know the answer. May be a functional one, but even then I am not sure: pure list is functional (there is no set: no side affects), but as it has lambdas it is possible to implement set. Could you write a compiler that enforces no use of set, it would have to detect all implementations of it. You could remove lambdas from the language, but that would be worse. Mar 13, 2016 at 17:37
  • Ohh I just thought of a language C++: a const method can not call a not const method (though you will need the correct compiler checks turned on, and not try to hard to get around it.) Mar 13, 2016 at 17:38
-10

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

4
  • Um, no. A procedure does not return anything. You're talking about side-effects, which are possible with both (if allowed by the language).
    – Mogsdad
    Aug 12, 2015 at 15:15
  • A procedure can return any amount of values, that amount may be zero Feb 14, 2016 at 13:28
  • A side-effect would be if a had an array and passed it into a function or procedure that found the biggest value, the array would be passed by reference and after the sub-routine has run the array is sorted, the fact that it is sorted is a side-effect, the value returned is the biggest value in the array Feb 14, 2016 at 13:44
  • I like this answer, and also like those with several downvotes because in some way are kinda right so, paradoxically, in order to make it very popular in SO I will give it a downvote. A Stored Procedure in SQL Server returns a resultset (what you referred to as "multiple values") whereas a function can only return one value (which is not very accurate since you can also create a Table-Valued Function).
    – user2188550
    Nov 12, 2019 at 15:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.