Hello, C ++ (24) is a big box! 5.1.1 function declaration and definition, and 5.1.1 Declaration

Source: Internet
Author: User

Hello, C ++ (24) is a big box! 5.1.1 function declaration and definition, and 5.1.1 Declaration

Chapter 2 program function Encapsulation

After completing the powerful wage program V1.0, we have increased our confidence and began to explore the C ++ world in a deeper distance.

Now, we can use various data types to define variables to express the various data involved in the problem; use operators to connect these variables to perform operations; the program process control structure is used to control the complex processing process of the data, and finally the data is processed to obtain the result. This is the program. However, as the problem to be handled becomes more and more complex, the code of the program will naturally become more and more complex. If you place all program code in the main () main function, the main function will become more and more complex. This is like stacking everything in a warehouse. As things pile up more and more, the warehouse is gradually full of things, which seems messy and difficult to manage. In the face of a messy warehouse, the smart Warehouse administrator provides a good way to manage it: put things in different categories into the box, and then add labels on the box, manage these boxes.

This good method can also be used in program design, and the complex program code can be loaded into different boxes according to different functions. It can also make the entire program structure clear and easier to develop and maintain. The boxes used in the warehouse are wooden boxes, and the boxes used in the program are the "functions" we will introduce below ".

5.1 The function is a big "box"

As programs become more and more complex, we can divide complex programs into modules based on the principle of "divide and conquer", and code that completes the same function is divided into the same module, finally, a function is formed. Just like managing a warehouse, we always put similar things in the same box, and then manage these boxes to manage the objects in the whole warehouse. In program design, we also put the code that completes a specific function independently into a function, then, a large function is completed through the combination of these functions.

Let's take a simple example: When reading a book and reading it, we want to eat instant noodles. This is actually a very complicated process. We need to wash the pot first, then boil the water, boil the water, then soak the noodles, and then wash the dishes after eating the noodles. If the entire process is expressed in the main function, the main function will be very complex and the structure will be very chaotic. In this case, the entire process can be divided into multiple small steps, and each small step is expressed using an independent function, finally, the complex process is completed by calling these functions in the main function, which makes the main function of the program simple and clear. 5-1.

Another important advantage of using function encapsulation is that functions can be repeatedly called by different modules for code reuse. This is like placing a box in this warehouse or another warehouse. For example, you can call the boiling function for instant noodles or the boiling function for instant noodles. In this way, you only need one boiling function to meet the needs of the boiling function in the process of instant noodles and instant noodles, it saves both time and effort. Since functions have so many benefits, let's take a look at how to define and use functions.


Figure 5-1 encapsulate the program into a box and conquer it separately

5.1.1 description and definition of functions

To use variables to express data in a program, we must declare and define variables before using them. Similarly, to use functions to express the computing process in a program, we also need to declare and define functions first. In C ++, the syntax format for declaring a function is as follows:

Return Value Type identifier function name (form parameter table );

For example, the following code declares an Add () function to calculate the sum of two integers:

int Add(int a, int b);

Compare with the syntax format of declared functions, the following describes each part of this function declaration.

1. Return Value Type identifier

After a function is executed, it is often necessary to return a data to its caller, indicating the result or other meaning of the function execution. The return value type identifier of the function is the data type of the returned data. For example, after the preceding Add () function is executed, it must return the addition result data to its caller. The result data type is int, therefore, in the declaration, we specify the return value type as int, indicating that the function will return an int type value to its caller after addition calculation, this value is the result of addition calculation of the Add () function. Therefore, we usually use this method to obtain the function execution result data. If the function only performs some actions and does not need to return result data, you can use "void" as the type of returned value, indicating that the function does not return data.

2. Function Name

The function name is used to identify a function. Just like the label attached to the box, we can find the box through the tag, you can also call the function to execute the code. The naming rules for functions are the same as those for variables. If the name of a variable indicates what the variable is, the name of the function indicates what the function is going to do ", in this sense, the function name is often a verb or a verb. For example, in the above example, the function needs to complete the addition operation of two numbers and execute the "Add" operation. Therefore, we will name this function "Add ).

3. Form parameter table

When calling a function, data exchange between functions is often required to pass in data to or from a function. Function parameters are used for data exchange, while the form parameter table describes function parameters. It mainly describes the number of parameters, specific data types, and parameter names. The syntax format is as follows:

Data Type 1 parameter name 1, data type 2 parameter name 2...

In the Add () Addition function declaration above, the "int a, int B" in the brackets after the function name is its form parameter table. It indicates that this function has two int-type parameters, the parameter names are a and B. The form parameter table of the Add () function must be designed as this is because the function requires two int types of data as the number to be added, so in order to pass the required data to the function, the formal parameter table contains two int-type parameters. to distinguish them, they are named a and B respectively. When using the function form parameter table, you need to pay attention to the following points.

(1) formal parameters must have clear data types.

The definition of a function parameter is similar to that of a defined variable. The data type of the parameter is always first written, and then the parameter name is written. For example, in the above example, "int a" is used as the Data Type of the corresponding parameter to transmit an int type data to the function. a is the name of the parameter. When you want to transmit multiple data to a function, you can define multiple parameters in the form parameter table. Each parameter is separated by a comma. For example, "int a, int B" in the above example defines two parameters a and B. In the form parameter table, each parameter must have a clear description of the data type. Even if the two parameters have the same data type, you cannot use the same data type specifier to define multiple parameters. For example, in the above example, although the data types of parameters a and B are the same, the form parameter table cannot be written as "int a, B", which is different from the definition variable.

Best Practice: Use const to modify parameters to prevent accidental modification of parameters

When we define some variables with fixed values, we can use the const keyword to modify them to prevent the value from being mistakenly modified, if the value of a parameter remains unchanged throughout the function execution process, for example, if the parameter is only used to pass data into the function, we can also use the const keyword to modify it, this prevents this parameter from being accidentally modified during function execution, thus avoiding errors. For example:

// Protect the parameter value from being modified with the const keyword
int Add (const int a, const int b)
{
     // error: attempt to modify a parameter modified with const
     a = 1982;
     b = 1003;

     return a + b;
}

Here, the two parameters of the Add () function only serve to pass data into the function. During function execution, the value should not be modified. Therefore, we add the const keyword to the function declaration to modify it, indicating that this is a read-only input parameter. If we mistakenly modify this parameter in the function, the compiler will give an error message to prevent accidental modification of the parameter value and avoid errors.

(2) formal parameters can have default values.

When defining a variable, you can specify the initial value of the variable. You can also specify an initial value for the parameter. A parameter with an initial value can be used without a specific value. For example, you can write a function to determine whether a score has passed. Passing or not is the result of comparing the current score with the passing score. This means that this function requires two parameters, one passing the current score to the function, and the other passing the passing score. In most cases, the pass score is 60, and 60 can be used as the default value of this parameter:

// determine whether a certain score exceeds the passing score, the default passing score is 60
bool IsPassed (int nScore, int nPass = 60);

Using the default parameter values can bring great flexibility to function calls. In most cases, if the default value is used for a parameter, You can omit the parameter with the default value when calling the function, and directly use other parameters to call the function. In this case, the omitted parameter value is the initial value specified during declaration. In some special cases, other specific values can be used as parameters to call a function. At this time, the parameter value is no longer the initial value in the function declaration, it is the specific value given when the function is called. For example:

int nScore = 82; // current score
// use the default value of the parameter
// At this time, the value of the omitted nPass parameter is the initial value of 60 in the function declaration
// It is equivalent to calling IsPassed (nSocre, 60)
IsPassed (nSocre);
// The result is not satisfactory, lower the passing score. Do not use the default value of the parameter, call the function with a specific value
// At this time, the value of the nPass parameter is the value given when the function is called. 56
IsPassed (nSocre, 56);

Note that the parameter with the default value should be at the end of the form parameter table. Parameters with default values cannot be defined at the beginning or center of the formal parameter table. For example:

bool max (int a = 0, int b); // In the wrong form, the default parameter cannot be at the beginning of the formal parameter list
bool max (int a, int b = 0); // correct form, the default parameter is at the end of the formal parameter list

(3) If there is no form parameter, you can use void instead.

A formal parameter of a function is not required. When a function simply performs an action and does not need to pass data between the function parameter and the caller, parameter tables in the form of functions are redundant. In this case, the form parameter table can be omitted directly, or the form parameter table can be replaced with "void", indicating that this function has no form parameter table. For example:

// leave the formal parameter list empty
void DoSomeThing ();
// or use void instead of formal parameter list
void DoAnotherThing (void);

Although the two forms can indicate that the function has no parameters, there is a difference in calling: if you leave the form parameter table blank, you can use any actual parameter to call this function. In form, it seems that a function call uses parameters, but in fact these parameters do not have any effect at all. If void is used as a function parameter, the actual parameter can only be blank during the call. For example:

// Correct: call the function with the formal parameter list blank with the string as the parameter
DoSomeThing ("cook");
// Correct: calling the same function with a formal parameter list left blank with an integer
DoSomeThins (1982);

// Error: Investigate functions with integers as parameters
DoAnotherThing (1982);

Leave the form parameter table of the function empty or use void instead to achieve the function's no-parameter purpose. This intention is more intense and obvious only when void is used as a formal parameter. It is not only explicitly indicated by void in the function declaration, in addition, no parameters can be used for function calls. Therefore, if we want to explicitly express a function without parameters, we 'd better use void.

The completion of the function declaration is only the first step to load the program code into the function box. It is equivalent to marking the function box, code that indicates what function is installed in the box (function name), and what data is required for the Code Execution (form parameter table ), finally, what data will be returned (return value type ). The second step is the key. to define a function, you must use the specific program code inside the function to process data to implement the function, in this way, the program code is finally loaded into the function box. The definition of a function is usually followed by the declaration of the function. The syntax format is as follows:

Return value type identifier Function name (formal parameter table)
{
     // function definition
}

The Code enclosed by a pair of braces "{}" after the function declaration is the definition of a function, also known as the function body. In the function body, we use the data passed in by function parameters to perform operations on the data with specific program code to implement specific functions of the function, finally, the "return" keyword is used to return the execution result data to the caller of the function. For example, you can define the Add () function declared above to Add two numbers and return their calculation results.

// calculate the sum of two numbers
int Add (int a, int b) // function declaration
{
     // function definition
     // Use the data passed in as a parameter to perform a summation calculation to achieve data processing
      int nRes = a + b;
    
     // Use the return keyword to return the result data of the function execution
     return nRes;
} 

In this code, the code enclosed in curly brackets after the function declaration is the function body of the Add () function. This function has only two statements. The first sentence "int nRes = a + B;" is the sum of the two numbers passed in by the calculation parameters a and B, and save the calculation result to the variable nRes, so that the function can be added (Add). The second sentence is "return nRes ;", that is, the result data stored in nRes is returned to the caller of the function through the return keyword. In this way, the function implements the function of calculating the sum of two numbers.

Here, the return keyword is a frequently used keyword in C ++. "return" refers to "return". When the function executes the return keyword, the function will immediately end execution and return, even if there is code after return, it will not be executed. If a function returns a value, it is also responsible for returning the result data to the function caller. The return result type must be the same as the return value type in the function declaration. Depending on the execution of the program, the same function can have multiple return statements, which are used to return different results under different circumstances. Of course, for functions that do not need to return results, do not write a return statement. The function body ends naturally after all the code is executed.

Best Practice: separate declarations and definitions

In actual development practices, functions defined in a source file are often called in another source file. In addition, for some function libraries (such as DirectX), we hope that others can use the functions in the function library, but do not want to expose the implementation details of the function to users. In this case, we usually adopt the following method: To provide function declaration only to function users, and users will know how to call the function according to the function declaration. For specific function implementation, it is written in another function implementation file, or through the dynamic link library file (for example ,. dll files) or static link library files (such ,. lib file) to the user of the function. In this way, all source code files of a program are generally divided into two types: one type of files is mainly used to record the declarations of functions or classes and provided to others or other files in the program for use. This type of file is called the header file. h is the suffix of the file name. Another type of file is used to define functions and classes to implement specific functions of functions and classes. Such files are called source files. cpp is the suffix of the file name.

In this way, the declaration and definition of a function are placed in two files respectively, implementing the separation of interfaces and implementations.


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.