In-depth discussion: differences between macro and inline functions and common functions

Source: Internet
Author: User

The execution process of inline functions is similar to the macro definition with parameters, but the processing of parameters is different. Macro definitions with parameters are not calculated, but replaced directly.
Inline functions are functions first, which means that many of the functions are suitable for inline functions. That is, inline functions evaluate the parameter expressions first,
Then pass the expression value to the form parameter.
Another difference between an inline function and a macro with parameters is that the parameter type and return value type of an inline function are explicitly specified in the declaration.
Macro-defined parameters do not have the concept of type. The Compiler checks the syntax only after the macro is expanded. This poses many security risks.
Pay attention to the following issues when using inline functions:
1) The definition Declaration of the inline function should appear before the first call to the function.
2) inline functions are first functions. Many functions are suitable for inline functions. For example, inline functions can be reloaded.
3) loop statements and switch results are not allowed in inline functions. Functions with abnormal interface declarations cannot be declared as inline functions.
Let's talk about the differences between macros and functions:
1. macros are used to replace simple strings (note that the replacement of strings is not the replacement of other types of parameters), while function parameters are transmitted with data classes.
Type, can be a variety of types.
2. Macro parameter replacement is directly processed without computation, while function calling transfers the value of real parameters to the form parameter. Since it is a value, it is naturally calculated.
3. The macro is executed before compilation. That is, the macro name is replaced with the macro name and then compiled. The function is called only after compilation and execution. Therefore, the macro occupies
Is the compilation time, while the function occupies the execution time.
4. macro parameters do not occupy memory space, because they only replace strings, while parameter transmission during function calls is information transmission between specific variables.
As a local variable of the function, the memory usage is obvious.
5. The call of a function requires a certain amount of time and space overhead, because the system should keep the field when calling the function, and then transfer it to the called function for execution. After the call,
Return to the main function, and then restore the site. These operations are obviously not available in the macro.
Now let's look at the inline function:
The so-called "inline function" is to embed a very simple function "into the code that calls his program. The purpose is to avoid the 5th points mentioned above.
Saves the time and space overhead of the original function call. However, you must note that as an inline function, the function body must be very simple and cannot contain loops, conditions, and selections.
Or other complex structures. Otherwise, it cannot be used as an inline function. In fact, even if you do not specify a function as an inline function, some compilation systems will automatically
A single function is used as an inline function. For a complex function, the system will ignore it even if you specify it as an inline function.

Before introducing inline functions, it is necessary to introduce preprocessing macros. Functions of inline functions and preprocessing of macros
Similar functions. We believe that we have used preprocessing macros. We often define some macros, such
# Define TABLE_COMP (x)> 0? (X): 0)
A macro is defined.

Why use Macros? Because the function call must transfer the execution order of the program to the Function
An address stored in the memory. After the program content of the function is executed, it is returned to the intermediate execution.
Before the function. This transfer operation requires that the site be stored and stored for execution before the transfer.
Site, after the transfer back to the site to restore, and continue to execute according to the original save address. Therefore, a function call must have
The fixed time and space overhead will affect its efficiency. Macros are only used in preprocessing.
Code expansion does not require additional space and time overhead. Therefore, calling a macro is better than calling
Functions are more efficient.

  However, there are many unsatisfactory aspects of Macro.
1. Macros cannot access private members of objects.
2. macro definition is easy to generate two meanings.
For example:
# Define TABLE_MULTI (x) (x * x)
We use a number to call it, TABLE_MULTI (10), so there seems to be no error,
The result returns 100, which is correct. However, if we call TABLE_MULTI (10 + 10,
The expected result is 400, while the macro call result is (10 + 10*10 + 10) and the result is 120.
However, this is not the expected result. To avoid these errors, add brackets to macro parameters.

# Define TABLE_MULTI (x) * (x ))

In this way, the macro is still possible even if this definition is used.
An error occurs. For example, if you use TABLE_MULTI (a ++) to call it, they want to get (a + 1) * (a + 1)
Results, but what is actually? Let's take a look at the macro expansion result: (a ++) * (a ++), if the value of a is
4. The result is 5*6 = 30. The expected result is 5*5 = 25, which causes another problem.
In fact, these problems also exist in some C library functions. For example, Toupper (* pChar ++) will
PChar executes the ++ operation twice because Toupper is actually a macro.

We can see that macro has some unavoidable problems. How can we solve them?

The following describes how to use inline functions to solve these problems. We can use inline functions.
To replace macro definition. In fact, we can replace the pre-processing macro With inline functions.

The difference between an inline function and a macro is that a macro is replaced by a Preprocessor for macro operations, while an inline function is
Implemented through compiler control. In addition, the inline function is a real function, only when necessary.
Inline functions are expanded like macros. Therefore, the parameter pressure stack of the function is canceled, reducing the open
Sales. You can call an inline function just like calling a function, without having to worry about
Some problems.
We can use Inline to define Inline functions. However, any function defined in the description section of the class
The number is automatically considered as an inline function.

  Next we will introduce the usage of inline functions.

Inline functions are valid only when they are declared together with the function body. Such a statement
Inline Tablefunction (int I) is ineffective. The Compiler just uses the function as a common function.
Number Declaration, we must define the function body.

Inline tablefunction (int I) {return I * I };

This defines an inline function. We can call it like a common function.
. However, the execution speed is indeed faster than that of common functions.

We can also define external functions defined in the class as inline functions, such:Copy codeThe Code is as follows: Class TableClass {
Private:
Int I, j;
Public:
Int add () {return I + j ;};
Inline int dec () {return I-j ;}
Int GetNum ();
}
Inline int tableclass: GetNum (){
Return I;
}

All the three functions stated above are inline functions. In C ++, the function body is defined inside the class.
Function, which is an inline function by default. Whether or not you have the inline keyword.

Inline functions are the most widely used in C ++ classes and should be used to define access functions. What we define
Classes are usually defined as private or protected data members, so that the outside world cannot directly read and write me
Data of class members.
To read and write private or protected members, you must use the member interface function. If we set
If these read/write member functions are defined as inline functions, the efficiency will be improved.Copy codeThe Code is as follows: Class sample {
Private:
Int nTest;
Public:
Int readtest () {return nTest ;}
Void settest (int I) {nTest = I ;}
}

Of course, inline functions also have some limitations. That is, the Execution Code in the function cannot be too much, such
If the function body of the inline function is too large, the general compiler will discard the inline method and use the common method.
Call a function. In this way, the efficiency of inline functions is the same as that of normal functions.

Macro usage
/* This series of articles, "C ++ Tips", is recommended to engineers by the company's Code Committee experts. I feel very good and can help you improve it together. No
Knowing how much will make people different. The real difference lies in how much you can do.
Many programmers do not know what the "macro" in C really means? In particular, macros and functions are often confused when they have parameters. Here I want
Let's talk about "macro". A macro is just a definition. It defines a statement block. When a program is compiled, the compiler must first execute an action of "replacing" the source program.
To replace the macro reference with the statement block defined by the macro, just like replacing the text file. This action term is "macro expansion ". Macro usage is more dangerous
Because you don't know what the Macro will look like after expansion. For example, the following macro:
# Define MAX (a, B) a> B? A: B
When we use macros like this, there is no problem: MAX (num1, num2); because the macro is expanded to num1> num2? Num1: num2 ;. However, for example
If this is the case, MAX (17 + 32, 25 + 21); and an error occurs during compilation. The reason is: 17 + 32> 25 + 21 after macro expansion? 17 + 32: 25 + 21,
Woh, what is this?
Therefore, when using a macro, you must add brackets to the parameters. The example above is changed to the following to solve the problem.
# Define MAX (a), (B) (a)> (B )? (A) B)
Even so, there is still a Bug in this macro, because if I call MAX (I ++, j ++) like this; after this macro, I and j are both accumulated
This is not what we want. Therefore, you should be careful when using macros, because the results of macro development are very unpredictable. And even though,
Macro execution is very fast (because there is no function call overhead), but the Macro will make the source code crash and increase the size of the target file (for example, a 50-line macro, Program
There are 1000 places to use, and the macro expansion will be very difficult), on the contrary, it cannot make the program run faster (because the execution file grows, the system frequently changes pages during running)
).
Therefore, be careful when deciding whether to use a function or a macro.

The inline Function Definition in C ++ is very simple. You only need to add a keyword inline before a common function. In addition, there is no such thing
Differences (including the function call method), because of this, in the opinion of many C ++ beginners (or even some people with C ++ programming experience), inline only
This is a concept. In fact, this is not a thorough understanding of inline functions. Let's talk about the differences between inline functions and common functions and macros.
LetterAfter reading the following sections, you must have a good understanding of the three.
The biggest difference between an inline function and a common function is the internal implementation, rather than the surface form. We know that when a common function is called, the system
First, jump to the entry address of the function, execute the function body, and then return to the place where the function is called. The function has only one copy.
Inline functions do not require addressing. When an inline function is executed, this function is expanded (similar to macro usage). If this function is called at N
Inline function, then this function will copy N code segments.
From the perspective of inline function calls, it improves the code execution efficiency because it lacks an addressing process, but this is at the cost of space.
.
For a function declared as inline, its code segment cannot be too long or too long. Some compilers consider it as a common function (the length of the function body exceeds the limit,
It seems that there is no rule, and this is indeed not a good rule, I personally think it should be determined by the logic of the function body ).
The following is an example of an inline function declaration:
Inline void SetVal (int a) {m_ B = };
Inline int GetVal () {return m_ B };
From the above example, we can see that the declaration and implementation of inline functions are usually in a file (usually in. h ).
Let's talk about the difference between inline functions and macros. In many documents, when talking about inline functions, inline functions are similar to macros,
It seems similar. After all, we cannot swap the two.
The similarities between the two are that the compiler will expand its code during execution and continue the following processing after execution. The difference is that macro
It is a simple text replacement, which does not return values, nor does it have the concept of common function parameters; while inline functions have the characteristics of common functions, such as the parameter list,
Return Value. The following is an example:
1. # define COUNT (X) (X * X) // a macro that calculates the product.
2. inline int count (int x) {return x * x} // an inline function for calculating the product

Printf (COUNT (3); // The result is COUNT (3) (3*3) = 9;
Printf (count (3); // The result is count (3) {return 3*3} = 9;

The above example does not seem to indicate the difference between the two. Let's change the call in the above example and look at the result.

Printf (COUNT (2 + 3); // The result is COUNT (2 + 3) (2 + 3*2 + 3) = 11
Printf (count (2 + 3); // The result is count (2 + 3) {return 5*5;} = 25;

If the macro is to reach the result of the product of 25, it should be written as follows:
# Define COUNT (X) * (X ))
Corresponding to the example above is # define COUNT (2 + 3) (2 + 3) * (2 + 3 ))

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.