C language-Function

Source: Internet
Author: User

What is a function?
A function is a self-contained unit of program code used to complete a specific task.
Why use functions?
First, you can skip writing duplicate code. If a program needs to use a specific function multiple times, you only need to write a suitable function, that is, the function can be written at a time and called multiple times. Second, functions can be modularized and easier to read and modify.
We can regard the function as a "black box", that is, a certain input will generate a specific record or return a certain value, the internal behavior of the black box does not need to be considered (unless it is the function writer ). Looking at the function in this way helps you focus on the overall design of the program rather than the implementation details.

A simple program:
1/* Create an asterisk */
2 # include <stdio. h>
3 # define NAME "Owen_beta"
4 # define WIDTH 40
5
6 void starbar (void);/* declare the function prototype. [Note that there are commas] */
7
8 int main (void)/* main () function */
9 {
10 starbar ();/* calling function */
11 printf ("% s \ n", NAME );
12 starbar ();
13}
14
15 void starbar (void)/* function definition */
16 {
17 int count;/* because the function is a "black box", count is a local variable.
18 is invisible in the main () function */
19 for (count = 1; count <= WIDTH; count ++)
20 {
21 putchar ('*');/* putchar function (character output function) is used to output a character to the terminal */
22}
23 putchar ('\ n ');
24}

Function Analysis:
1. Starbar identifiers are used three times in different locations: the function prototype informs the compiler of the function type of starbar (); the function call causes the execution of the function; the Function Definition specifies the specific implementation of the "black box ".
2. Functions are of the same type as variables. Any program must declare the function type before using the function.
In the above example:
Void starbar (void)
Parentheses indicate that starbar is a function name. The first void indicates the function type: the function has no return value. The second void in parentheses indicates that this function does not accept any parameters. The role of a semicolon is to declare a function rather than define a function. That is to say, this row declares that the program will use a function named starbar () and the function type is void, and notifies the compiler to find the definition of this function elsewhere.
3. It is recommended that the function type be placed before the main () function to facilitate reading.
4. The program calls the starbar () function in the form of a function name followed by parentheses and semicolons in main ().
1 starbar ();/* calling function )*/
5. in the program, starbar () and mian () have the same definition format, that is, they start with type, name, and parentheses, then start curly braces, variable declarations, function statement definitions, and end curly braces.
As shown in the following procedures
1 # include <stdio. h> // preprocessing command
2 # define WIDTH 40 // preprocessing command
3
4 void starbar (void) // function name
5 {
6 int count; // statement
7 for (count = 1; count <= WIDTH; count ++) // loop control statement
8 {
9 putchar ('*'); // Function
10}
11 putchar ('\ n ');
12}
 

If you do not want to use an asterisk, do you want to enter a blank line? What should I do? We certainly want to write a function to open spaces.
In fact, this is a waste of time. You can write a common function to print spaces.
1 # include <stdio. h>
2 # define NAME "Owen_beta"
3 # define WIDTH 40
4 # define SPACE''
5
6 void show_n_char (char ch, int num); // define the function prototype. Remember to have a comma.
7
8 int main (void)
9 {
10 int spaces;
11 show_n_char ('*', WIDTH );
12 putchar ('\ n ');
13 spaces = (WIDTH-strlen (NAME)/2)/2; // calculates the number of spaces before NAME
14 show_n_char (SPACE, spaces); // enter a SPACE
15 printf ("% s", NAME );
16 putchar ('\ n ');
17 show_n_char ('*', WIDTH );
18}
19
20 void show_n_char (char ch, int num)
21 {
22 int count;
23 for (count = 1; count <= num; count ++)
24 {
25 putchar (ch );
26}
27}

The above program uses the concept of "form Parameters", as follows:
Void show_n_char (char ch, int num) // Function Definition
{
....
}

This line of code notifies the compiler show_n_char () to use two parameters named ch and num, whose types are char and int, respectively. The ch and num variables are formal parameters, and the formal parameters are local variables. They are private functions.
 
We noticed that there is a piece of code in the main () function.
1 show_n_char (SPACE, spaces); // enter a SPACE for www.2cto.com.
SPACE and spaces are the actual parameters. The actual parameter is the specific value of the function variable to be a form parameter. Because the value used in the called function is copied from the called function, no matter what operation is performed on the copied value in the called function, the original value in the called function will not be affected.
 
Summarize the actual parameters and form parameters:
The actual parameter is that the function call is an expression that appears in parentheses, while the formal parameter is a variable declared in the function header in the function definition.
 
The communication methods from calling a function to called function are described above. If you want to transmit information in the opposite direction, you can use the function return value. We can use return to return values from the function.
1/* Find the minimum values of two integers */
2 # include <stdio. h>
3 int imin (int, int);/* in the function prototype, We can omit the variable name as needed */
4
5 int main (void)
6 {
7 int evil1, evil2;
8 printf ("Enter a pair of integer (q to quit): \ n ");
9 while (scanf ("% d", & evil1, & evil2) = 2)
10 {
11 printf ("The lesser of % d and % d is % d \ n", evil1, evil2, imin (evil1, evil2);/* function call */
12 printf ("Enter a pair of integer (q to quit): \ n ");
13}
14 printf ("Bye \ n ");
15 getch ();
16 return 0;
17}
18
19 int imin (int m, int n)/* function definition */
20 {
21 int min;
22 if (m <n)
23 min = m;
24 else
25 min = n;
26}

The return keyword indicates that the following expression is the return value of the function.
The variable min is private to imin (), but the return statement returns the value of min to the call function. The following statement assigns the min value to lesser
Lesser = imin (m, n );
But can we use the following sentence?
1 imin (m, n );
2 lesser = min;

The answer is no !! Because the calling function does not know the existence of the min variable. The variable in imin () is the local variable of the function. As we mentioned earlier, the function is a "black box", and the content in it is invisible to the main () function.
 
We can also use the following code to simplify the program.
1 int imin (int m, int n)/* function definition */
2 {
3 return (m <n )? M: n;
4}

 
Another function of the return Statement is to terminate the execution of the function and return the control to the next statement that calls the function. The execution result of a return statement is not the last sentence of a function. Therefore, we can analyze imin () functions in this way.
1 int imin (int m, int n)/* function definition */
2 {
3 int min;
4 if (m <n)
5 return m;
6 else
7 return n;
8}

You can also use the following sentence
Return;
This statement terminates the execution of the function and returns the control to the called function. Because there is no expression after return, there is no return value. This form can only be used in void functions.
 
To further understand the function's "black box" nature, the program is as follows:
1 # include <stdio. h>
2 void mikado (int);/* declare the function prototype */
3
4 int main (void)
5 {
6 int pooh = 2, bah = 5;
7 printf ("In mian (), pooh = % d and & pooh = % p \ n", pooh, & pooh );
8 printf ("In main (), bah = % d and & bah = % p \ n", bah, & bah );
9 mikado (pooh );
10 return 0;
11}
12
13 void mikado (int bah)/* function definition */
14 {
15 int pooh = 10;
16 printf ("In pikado (), pooh = % d and & pooh = % p \ n", pooh, & pooh );
17 printf ("In mikado (), bah = % d and & bah = % p \ n", bah, & bah );
18}

Output:
In mian (), pooh = 2 and & pooh = 0028FF1C
In main (), bah = 5 and & bah = 0028FF18
In pikado (), pooh = 10 and & pooh = 0028 FEEC
In mikado (), bah = 2 and & bah = 0028FF00

The output above illustrates several problems:
First, the two pooh variables have different addresses, and the same is true for the two bah variables, proving the "black box" nature of the function. Second, the main () function calls mikado (pooh) the actual parameter (pooh value 2 in main () is passed to the form parameter in mikado (int bah. Note: This transfer is only a numerical value, and the two variables (pooh in main () and bah in mikado () maintain the original features respectively, once again, it proves the "black box" nature of the function.
 
Change the variable in the called Function
What if we want to exchange variables? Maybe we will use the following program
1 # include <stdio. h>
2 void interchange (int u, int v);/* declare the function prototype */
3 int main (void)
4 {
5 int x = 5, y = 10;
6 printf ("Originally x = % d and y = % d. \ n", x, y );
7 interchange (x, y );
8 printf ("Now x = % d and y = % d. \ n", x, y );
9 return 0;
10}
11
12 void interchange (int u, int v)/* function definition */
13 {
14 int temp;
15
16 temp = u;
17 u = v;
18 v = temp;
19}

Output:
Originally x = 5 and y = 10.
Now x = 5 and y = 10.

However, this is a wrong program and the variables in the called function have not changed. Temp, u, and v in void interchange (int u, int v) are all local variables and they are all in the "black box", which is invisible to main. Changes to variables in the function do not affect the variables in main. We can verify it through the following program:
1 # include <stdio. h>
2 void interchange (int u, int v);/* declare the function prototype */
3 int main (void)
4 {
5 int x = 5, y = 10;
6 printf ("Originally x = % d and y = % d. \ n", x, y );
7 interchange (x, y );
8 printf ("Now x = % d and y = % d. \ n", x, y );
9 return 0;
10}
11
12 void interchange (int u, int v)/* function definition */
13 {
14 int temp;
15
16 printf ("Originally u = % d and v = % d \ n", u, v );
17 temp = u;
18 u = v;
19 v = temp;
20 printf ("Now u = % d and v = % d. \ n", u, v );
21}

Output:
Originally x = 5 and y = 10.
Originally u = 5 and v = 10.
Now u = 10 and v = 5.
Now x = 5 and y = 10.

In this way, we once again prove the "black box" Nature
 
Maybe we can use return to return the value and change the value. However, the return statement can pass only one value to the call function, while the value exchange must pass two values to the call function.
It can be implemented with pointers!
1 # include <stdio. h>
2 void interchange (int * u, int * v);/* declare the function prototype */
3 int main (void)
4 {
5 int x = 5, y = 10;
6 printf ("Originally x = % d and y = % d. \ n", x, y );
7 interchange (& x, & y);/* Transfer address to function */
8 printf ("Now x = % d and y = % d. \ n", x, y );
9 return 0;
10}
11
12 void interchange (int * u, int * v)/* function definition */
13 {
14 int temp;
15 temp = * u;
16 * u = * v;
17 * v = temp;
18}

In this way, a value exchange is performed.
 
Complete.

From owen-beta
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.