Procedures and functions
Course Navigation
<< Previous - Control structures | Next - Arrays, strings and records >> |
---|
Overview[edit | edit source]Programming can be a repetitive task. While we have structures like loops to help us do the exact same thing many times, there are times when we need to do something different with only slight variation each time. Rather than write the same code with only minor differences over and over, we group the code together and use a mechanism to allow slight variations each time we use it. A function (also called procedure or method) is a smaller program with a specific job. In most languages, functions can be "passed" data, called parameters, which allow us to change the values they deal with. For instance, a function which adds one to a number would take the number as an argument. Languages usually have a way to return information from a function, and this is called the return data. In our example, the function would return one plus the number which was passed as an argument. The programmer uses a function by calling it. An example is given in the C language. Lines beginning with // are comments that do not represent any actual code. // first we declare the function, and tell the compiler that it takes one // argument named x, which is an integer, and returns one integer value int add_one(int x) { // now, inside of the function, we return the new value return x + 1; } // this is the main part of the program, which calls the function we declared earlier main() { int n; n = add_one(2); // this line will simply print the value of n to the screen. In our case this is 3 printf("%i", n); } Parameters are often referred to as arguments. A fine distinction between parameters and arguments can be made, however. A parameter (or formal parameter) is a characteristic of a function while an argument (or actual parameter) is a characteristic of a function call. A parameter exists for a function, even without enclosing source code while the argument exists only in a running program when a call to the function is made. Parameters can be passed into a function with different semantics. The different ways to pass parameters are called call-by-value, call-by-strict-value, call-by-reference, call-by-name, call-by-result and call-by-value-and-result. The first three are the more common forms.
|
|