Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a "function" and a "procedure"?

People also ask

What is difference between function and procedure in SQL?

A function returns a value and control to calling function or code. A procedure returns the control but not any value to calling function or code. A procedure has support for try-catch blocks. A select statement can have a function call.

What is the difference between function and procedure in C++?

A function is like a procedure but it returns a value; its definition begins with a type name, e.g. int or double indicating the type of value it returns. Procedure calls are statements that get executed, whereas function calls are expressions that get evaluated.

What is the relationship between a function and a procedure?

A procedure is a routine that can accept arguments but does not return any values. A function is a routine that can accept arguments and returns one or more values.


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.


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.


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.


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


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.