Procedures and functions
From Wikiversity
[edit] OverviewProgramming 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 they can be "passed" data, called parameters, which allow us to change the values they deal with. Languages usually have a way to return information, and this is called the return data. The programmer uses a function by calling it. For example
//eg C program
void print_my_num(int in)//<--- the function is declared, showing the placeholder where the data is passed (parameters)
{
printf("%i",in);
}
main()
{
print_my_num (100);//<---calling the function
}
/*WHAT WOULD SHOW UP ON THE SCREEN*/
100
An example of "returning" could look like this:
int double_my_num (int in)
{
return 2*in;
}
main()
{
printf("%i",double_my_num(5));
}
/*WHAT WOULD SHOW UP ON THE SCREEN*/
10
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.
|