|
Methods: an IntroductionMost programming languages allow you to divide your program into smaller parts. These can be called "sub-routines", "procedures", "functions" or "methods". In Pike, we use the term "method". Other parts of the program can call the method, i. e. cause it to be executed. How to create a methodTo create a method, you must define it, with a method definition. A method definition follows this template: access-modifiers type method-name( parameter-list ) method-body Here is a description of the various parts in the definition template:
Sometimes we talk of the head and the body of a method. The body is of course the method-body in the template above, while the head consists of everything in the method definition except the body. We can say that the method head is a description of the method: its name, which arguments it expects, and what type of value it will return. A part of the program that wants to call a method, needs to know about the head of that method, but not about the body. The method body, on the other hand, contains the statements that will be executed when the method is called. The body is therefore a description of what, and how, the method performs whatever it is that it does. Here is a simple example of a method definition: float average(float x1, float x2) { return (x1 + x2) / 2; } The method average returns the average of its two arguments. Both the return value and the two parameters are floating-point values. Here are some valid statements that contain calls to average: float x = average(19.0 + 11.0, 10.0); average(27.13, x + 27.15); float y = average(1.0, 2.0) + average(6.0, 7.1); float z = average(1.0, average(2.0, 3.0)); When a method has finished what it has to do, we say that it returns. The program will then continue executing immediately after the place of the method call. If the method has produced a value, we say that we return that value. The return statement is used to send a value from a method back to the point from where it was called: return expression;The return statement will also cause Pike to leave the method, and continue execution immediately after the point where the call to the method was made. You can have several return statements in the same method. If the method is defined to return void, you can use return without a value to leave the method: return;If you reach the end of the body of a method, without having returned first, the method will return, with no value. |
|||