C language review and improvement-V. Function

Source: Internet
Author: User
Tags call by reference
V. Function

C Programs are all composed of functions, which provide places for All Program activities.

I. Modular Design: we should learn to divide each module in the program reasonably. When designing a large business program, you can adopt a good strategy, that is, dividing a large program into small programs that are relatively independent and easy to manage and read. The key is to break it into several small blocks (modules) so that each module can be easily encoded. In the end, we need to carefully implement these modules and construct a complete program. This is the "top-down" Modular Design Model in software engineering.

1. The biggest advantage of the modular design mode is that the Code is easily reused.

2. Attention should be paid to the modular design model: What are the criteria for dividing functions? Pay attention to the cohesion and coupling of the program. Code that may be repeatedly called in a program should be defined as a module separately.

Organize related statements together and give them corresponding names. In this way, programs are segmented. This form of combination is a function.

Functions are implemented through the function call mechanism. Function call specifies the name of the called function and the information required to call the function (parameter list ).

The function that the programmer writes to complete a specified task is a user-defined function. The standard library function is a public function provided by C that can be used in any program.

3. In a complete C program, there is only one main () as the entry point of the program. Other functions are called directly or indirectly by main.

Ii. Function Definition and declaration:

1. return_type function_name (type var1, type var2 ,..., Type Varn) {/* function body */}

/** In c89, functions with int type can be returned without the int keyword, but neither c99 nor C ++ is allowed. * Note: In modern large commercial projects, the int keyword before the int type function cannot be omitted. * Otherwise, the compiler will not be able to perform parameter checks. ** note that the inline keyword is added to c99 and C ++. */

2. All functions must be declared before use: Use the function prototype from c89.

(1) return_type function_name (type, type ,..., Type);/* declare a function */

/** The parameter name is optional. However, when an error occurs, the compiler can identify any type of mismatch Based on the parameter name. * A statement must end with a semicolon. */

(2) Technically speaking, prototype is not necessary, but very useful. Must be used in both C ++ and Java. It helps to capture bugs in advance. The prototype allows the compiler to provide a stronger type check. It can find a problematic type conversion between the variables used to call a function and the parameter type, the difference between the variable number used to call the function and the parameter number in the function can be captured.

(3) If this function is defined before a function is used for the first time in a program, the function definition can be used as its declaration. However, in the development of large commercial software (generally there are many files), the program should contain a separate declaration of each function (this is actually the compiling method of C code ).

(4) Main () does not need to be declared. It is the entry point for program execution.

(5) variable length parameter list: return_type function_name (type var1 ,...); /* use... * // ** at least one parameter * int F1 (...) must be defined (...); this is invalid */

Principle: no matter how many parameters there are, consider them as strings, press the stack, and retrieve them one by one. [Example] printf () is the most typical example.

3. Notes:

(1) If the function does not have a parameter, use the void Keyword: int F1 (void) for declaration;/* If the parameter is called, an error occurs */Note the difference with C ++: void F1 ();/* void is not required */

(2) porting problem: In early versions of C, the function declaration only needs to tell the compiler function's return type. For example: int max ();/* basically obsolete */When porting to C ++, the variable type section must be added before Compilation: int max (INT, INT );

(3) ansi c supports two types of parameter definitions:

--> Classic format: Both c89 and c99 are supported, but C ++ is not. Therefore, problems may occur during transplantation. Ansi c has explicitly removed this method.

Int max (a, B) int A, B; {/* process */}

--> Modern form: c89, c99, and C ++ are supported (C ++ only supports modern form ).

Int max (int A, int B) {/* process */}

(4) declaration position:

--> Float F1 (float), F2 (float); void F3 (void); int main () {/* General Main () all are placed at the beginning * // * Processing */

Return 0 ;}

--> Int main () {float F1 (float), F2 (float); void F3 (void ); /* statements that declare other functions in the function body should be placed at the beginning (before all actions) * // * This method increases the difficulty of function management and is rarely used */

/* Process */

Return 0 ;}

Iii. function call: functions are represented in various forms, but they are essentially function calls. To be familiar with functions, you must first master the function call mechanism.

1. In computer languages, there are two ways to pass variables to subroutines:

-Call by value: it is a general method of C. It copies the variable value to the shape parameter of the subroutine. The modification of parameters does not affect the variables.

-Call by reference: Copies the variable address to the shape parameter of the subroutine, And the subroutine accesses the actual variable through the address. The modification of parameters can affect the values of variables used for subroutine calls.

[Example 1] value call [Example 2] Reference call # include <stdio. h> write the example int max () of the Reference call by yourself to see if you really understand that the reference calls int main () {int A = 1, B = 2; printf ("the big one: % d/N", max (A, B); Return 0 ;}

Int max (int A, int B) {return (A> B? A: B );}

2. recursion: The self-calling of a function is a process defined by yourself.

When a function calls itself, it allocates memory space for local variables and parameters in the stack zone, but does not copy the function code and only re-allocates the corresponding variables. When each recursive call returns, the space of its local variables and parameters is released, and the call points in the function continue to be executed.

Advantages of recursive Programs: it can generate clearer and more concise versions of some algorithms. In addition, some special problems (such as AI) are actually recursive, which is especially suitable for Recursive solutions and easier to think about than iteration.

Most recursion operations do not significantly improve memory efficiency. The recursive version of many programs is slower than the equivalent iteration version because the overhead of repeated calls is too large.

Excessive recursion may overflow the stack and overwrite other data or code of the program. Make sure that the recursive depth is not out of control.

When writing recursion, a condition judgment statement must be placed at an appropriate position for forced return. Otherwise, the function may never be returned after it is called. During development, printf () and getchar () can be used to monitor the running Progress and find errors.

[Example] ITOA () function: int --> char (ASCII code) conversion. # Include <stdio. h> void ITOA ();

Int main () {char * s; int N; scanf ("% d", & N); ITOA (N, S); puts (s );

Return 0 ;}

Void ITOA (int n, char * s) {int I = 0, J, power = 1; if (n <0) {s [I ++] = '-'; N =-N ;}

For (j = N; j/10; j/= 10) Power * = 10; s [I ++] = J + '0 ';

If (N/10) ITOA (n-J * power, S + I); else s [I] = '/0 ';}

Iv. function return values:

1. In c89, if a non-void function executes a return statement without a value, a useless value is returned. This is terrible.

2. During compilation, functions are classified into three types:

(1) calculation (pure function): specifically designed to return an operation-based value after performing an operation on a pair of variables.

(2) result (successful or failed) returned after processing: for example, fopen ().

(3) No obvious return value: This type of function is a strict process with no return value. It should be defined as void to prevent misuse.

[Note] the void keyword is not defined in early C versions. Therefore, in early programs, functions that do not return values can only be defined as int type by default.

3. Sometimes the return value is of little significance, for example, printf () returns the number of bytes written.

 

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.