Hello, C + + (24) So big a box! Declaration and definition of the 5.1.1 function

Source: Internet
Author: User



The 5th Chapter uses function encapsulation program function



After completing the powerful payroll program V1.0, we doubled our confidence and began to explore further afield in the C + + world.



Now, we can use a variety of data types to define variables to express the various data involved in the problem, using operators to join these variables to operate it, using the program flow control structure to control the complex processing of these data, the final implementation of data processing results, and this is the program. However, as the problems to be dealt with become more complex, the code of the program will naturally become more and more complex. If you put all the program code in the main () key function, the main function will become more and more complex. It's like stacking everything up in a warehouse, and as things pile up, the warehouses are piled up with things that are cluttered and difficult to manage. In the face of a cluttered warehouse, smart warehouse administrators provide a good way to manage: categorize things into boxes, then label them on boxes and manage them through them.



This good method can also be used in the program design, the complex program code in accordance with the function of different boxes, also can make the whole program structure clear, easier to develop and maintain. The boxes used in the warehouse are wooden boxes, and the boxes in the procedure are the "functions" we are going to introduce below.


5.1 function is a big "box"


In the process of becoming more and more complex, we can according to the principle of "divide and conquer", according to the different functions of the complex Program Module division, the same function of the code is divided into the same module, the final form of a function. Just like managing a warehouse, we always put things of the same kind in the same box, and then manage the boxes to manage the objects in the whole warehouse. In the program design, we also put together the relatively independent code to complete a particular function into a function, and then through the combination of these functions to complete a relatively large function.



To give a simple example: read a book to see the hungry, we want to soak instant noodles to eat. This is actually a very complicated process, we have to wash the pot, and then boil water, after boiling the surface, after eating noodles and washing dishes. If the whole process is expressed in the main function, then the main function will be very complex and the structure will be very chaotic. At this point, the entire process can be divided into small steps, and then each small step with a separate function to express, and finally in the main function through the organization call these functions to complete the complex process, so that the main function of the program becomes simple and clear, the structure is very clearly. As shown in 5-1.



Another important advantage of using function encapsulation is that functions can be repeated multiple times by different modules, enabling code reuse. It's like a box that can be placed either in this warehouse or in another warehouse. For example, the bubble surface can call the boiling water function, the same cooking rice can also call the boiling water function, so that only need a boiling water function, you can meet the bubble surface and cooking two process of boiling water function needs, both time and effort. Since the function has so many benefits, let's look at how to define and use the function.






Figure 5-1 Wrapping the program into a box, divide and conquer


Declaration and definition of the 5.1.1 function


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



Return value type identifier function name (formal parameter table);



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


int ADD (intint b);


Compare the syntax format of the declared function, and look at the individual parts of the function declaration below.


1. return value type identifier


After the function is executed, it is often necessary to return a data to its caller, indicating the result of the function execution or other meanings. The return value type identifier of the function is the data type of the returned data. For example, the Add () function above will need to return the add and result data to its caller after execution, and the result data type is int, so we specify its return value type int in the declaration, indicating that the function will return a numeric value of type int to its caller after the addition calculation is completed. This value is the result of the Add () function addition calculation. So we usually use this method to get the result data of the function execution. If the function simply performs some action and does not need to return the result data, you can use "void" as the type of the return value, indicating that the function does not return data.


2. Name of function


The function name is the name to identify a function, just like the label on the box, we can find the box by the tag, or we can call it through the function name to execute the code. A function's naming convention is the same as a variable's naming convention. If the variable name is a description of the variable "what", then the name of the function is to explain the function to "do what", so in this sense the function name is often a verb or noun. For example, in the above example, the function is to complete the addition of two numbers, which executes the "plus" action, so we'll name the function add (plus).


3. Form parameter table


When calling a function, it is often needed to exchange data between functions, passing in or out some data from the function. The parameter of the function is used for data exchange, and the formal parameter table is the description of the function parameter, it mainly describes the number of parameters, the specific data type and the name of the parameter. The syntax format is as follows:



Data type 1 Parameter name 1, data type 2 parameter Name 2 ...



In the above add () addition function declaration, the function name in parentheses after the "int A, int B" is its formal parameter table, which indicates that the function has a total of two parameters of type int, the parameter names are A and B respectively. The form parameter table of the ADD () function is designed so that the function requires two data of type int as summand, so in order to pass the required data to the function, the formal parameter table has two parameters of type int, and in order to differentiate, it is named A and B respectively. There are a few areas to note when using the formal parameter table of a function.



(1) Formal parameters should have a definite data type.



The definition of a function parameter is similar to defining a variable, always writing the data type of the parameter and then writing the name of the parameter. As in the above example, "int a", because to pass an int type of data to the function, so it is used to do the corresponding parameter data type, A is the name of the parameter. To pass multiple data to a function, you can define multiple parameters in the formal parameter table, with a comma interval between each parameter. For example, "int a,int B" in the example above defines two parameters A and B. In the formal parameter table, each parameter must have an explicit data type description. Even if the data type of the two parameter is the same, you cannot define multiple parameters using the same data type descriptor. For example, in the example above, although the data types of the parameters A and B are the same, the formal parameter table cannot be written as "int A, B", which is different from defining variables.



Best practice: Modify parameters with Const to prevent accidental modification of parameters



When we are defining some variable whose value is fixed, it is decorated with the Const keyword to prevent its value from being modified incorrectly, if the value of one parameter is fixed throughout the execution of the function, such as those that are only responsible for passing data inside the function. We can also use the Const keyword to decorate it, which prevents this parameter from being accidentally modified during the execution of the function to avoid 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 are just a function of passing in the data into the function, and the value should not be modified during the execution of the function. So we add the Const keyword to the function declaration to decorate it, indicating that this is a read-only passed in parameter. If we mistakenly modify this parameter in the function, the compiler will give the appropriate error to prevent the value of the parameter from being accidentally modified to avoid errors.



(2) Formal parameters can have default values.



You can give the initial value of a variable when defining a variable, as well as giving the parameter an initial value when defining the parameter. Parameters that have an initial value can use this initial value without giving a specific value at the time of the call. 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, which means that the function requires two parameters, one passes the current score to the function, and the other is responsible for passing the passing score. In most cases, the pass score is 60, then you can use 60 as the default value for 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 parameter defaults gives you a lot of flexibility in the invocation of the function. In most cases, if the parameter should use a default value, you can omit the parameter that has the default value when the function is called, and call the function directly with the remaining arguments. At this point, the value of the omitted parameter is the initial value specified at the time of declaration. In some special cases, the function can be called with other specific values as parameters, at which point the value of the parameter will no longer be the initial value in the function declaration, but 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); 


It is important to note that the parameter with the default value should be at the end of the formal parameter table. Parameters that have default values cannot be defined at the beginning or middle 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) When there is no formal parameter, void can be substituted.



The formal parameter of a function is not required, and when a function simply completes an action, it does not need to pass data between the function parameter and the caller, the form parameter table of the function is superfluous. At this point, you can either omit the formal parameter table directly, or use "void" instead of the formal parameter table, indicating that the function has no formal parameter table. For example:


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


Although both of these forms can represent functions without parameters, there is a certain difference in invocation: If you leave the formal parameter table blank, you can call the function with any actual arguments at the time of invocation. In form, it is as if the function call used parameters, but in fact these parameters do not have any effect at all, and if void is the formal parameter of the function, then the actual argument can only be empty when called. 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); 


Empty the formal parameter table of a function or use void instead, you can achieve the purpose of function without parameters. This intent is even more intense and obvious when using void as the formal parameter, not only in the function declaration, but with void to explicitly indicate that this is a parameterless function, and that no arguments can be used when the function is called. So, if we want to explicitly express the meaning of a function without parameters, it is best to use void.



Complete the declaration of the function, just the first step of loading the program code into the function box, which is equivalent to labeling the function box, indicating what functions the code (the function name) is loaded in the box, and what data (Form parameter table) is required for the execution of the code, and what data (return value type) will be returned in the end. The next step is the key, to complete the definition of the function, that is, in the function with the specific program code to handle the function of the data to implement functions, so that the program code is finally loaded into the function box. The definition of a function is often followed by the declaration of the function, with the following syntax:


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


The code enclosed by a pair of curly braces "{}" immediately after the function declaration is the definition of a function, also known as the function body. In the function body, using the data passed by the function parameter, we use the specific program code to operate the function, and finally return the execution result data to the caller of the function with the "return" keyword. For example, you can define the Add () function declared above, add two numbers, and return the results of their calculations.


// 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, a piece of code enclosed in curly braces after a function declaration is the function body of the Add () function. This function body has only two statements, the first sentence "int nres = a + b;" is to calculate the number of parameters A and B passed in the nres, and save the results of the calculation to the variable, so that the function sums (ADD), the second sentence is "return nres;", That is, the result data saved in Nres is returned to the caller of the function through the return keyword. In this way, the function body realizes the function of calculating the sum of two numbers.



The return keyword here is a very common keyword in C + +, which means "return", meaning that when the function executes to the return keyword, the function will immediately end execution and return, even if there is code behind the return and will not be executed. If the function has a return value, it is also responsible for returning the resulting data to the caller of the function. The result type returned by return 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 to return different results in different cases. Of course, for a function that does not need to return a result, you can not write the return statement, and the function body ends naturally after executing all the code.



Best practice: Declaration and definition Phase separation



In practical development practice, functions defined in one source file are often called in another source file. In addition, for some function libraries (such as DirectX), we want others to use functions in the library, but do not want to expose the implementation details of the function to the consumer. The usual approach is to provide the function's declaration only to the consumer of the function, and the consumer knows how to call the function based on the function declaration. For a specific function implementation, it is written in a separate function implementation file, either through a dynamic link library file (for example, a. dll file) or a static link library file (for example, a. lib file) to the user of the function. In this way, all source code files for a program are usually divided into two categories: a class of files that are used primarily to record functions or classes of declarations, to be provided to others or to other files in the program. Such files are referred to as header files, usually with. h as the file name suffix, and other types of files that define functions and classes to implement functions and classes, which are called source files, and more. CPP is the file name suffix.



Thus, the Declaration and definition of a function are placed in two files respectively, which realizes the separation of interface and implementation.



Hello, C + + (24) So big a box! Declaration and definition of the 5.1.1 function


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.