In programming, a self-contained software routine that performs a task. Functions can do a large amount of processing or as little as adding two numbers and deriving a result. Values are passed to the function, and values may be returned. Or, the function may just perform the operation and not return a resulting value. The concept of a function within a program is that, once written, it can be used over and over again without the programmer having to duplicate the same lines of code in the program each time that same processing is desired.
Standard and Programmer-Defined
Programming languages provide a set of standard functions as well as allow programmers to define their own functions. For example, the C and C++ programming languages are built entirely of functions and always contain a "main" function.
The Application Programming Interface (API)
Functions in one program can also be called for by other programs and shared. For example, operating systems can contain more than a thousand functions to display data, print, read and write disks and perform myriad tasks. Programmers write their applications to interact with the OS using these functions. This list of functions is called the "application programming interface" (API).
Functions are activated by placing a "function call" statement in the program. The function call often includes values (parameters) that are passed to the function. When called, the function performs the operation and returns control to the instruction following the call. The function may return a value or not. Writing a program in a language such as C/C++ involves calling language functions, one's own functions and operating system functions (APIs). There is a whole lot of function calling. See function prototype
A Function Call Example: Open and Read
The example below shows two very simplified API functions to open and read a file.
The OPEN function is called to read the file "budget.txt," and the function returns a value in the variable HANDLE. If the file was opened successfully, HANDLE might contain a positive number, but if not, a negative one. The value in HANDLE is then passed to the READ function to read so many bytes (LENGTH) of the file into a memory area called INPUTBUFFER. The OPEN function returns the number of bytes read in the SIZE variable.
handle = open("budget.txt");
size = read(handle, InputBuffer, length);