A further discussion: the difference between a macro, an inline function and a normal function _c language

Source: Internet
Author: User
Tags function definition
Inline functions are executed in much the same ways as with parametric macro definitions, but the parameters are handled differently. Macro definitions with parameters do not perform an operation on the parameters, but instead directly replace the
The inline function is the function first, which means that many properties of the function are applicable to the inline function, that is, the inline function first evaluated the parameter expression,
The value of the expression is then passed to the formal parameter.
Another difference between inline functions and parameter macros is that the parameter types and return value types of the inline function are specified explicitly in the declaration;
Macro-defined parameters have no concept of type, and the compiler checks the syntax only after the macro is expanded, which has a lot of security implications.
when using inline functions, you should be aware of the following issues:
1 The definition declaration of an inline function should appear before the first call to the function.
2 inline functions are first functions, and many properties of functions are applicable to inline functions, such as inline functions can be overloaded.
3 the loop and switch results are not allowed in inline functions, and functions declared with an exception interface cannot be declared as inline functions.
First, the difference between a macro and a function:
1. Macros do is a simple string substitution (note is the replacement of strings, not other types of parameters), while the function of the parameters of the pass, the parameter is a data class
Type, can be of various types.
2. Macro parameter substitution is directly processed without calculation, and function call is to pass the value of the argument to the formal parameter, since it is a value, naturally it is calculated.
3. Macros are made before compiling, that is, first replace the macro name with the macro body, and then compile, and the function is obviously compiled after the execution of the call. Therefore, the macro occupies the
Is the compile time, and the function occupies the time of execution.
4. Macro parameters do not occupy the memory space, because only to do the replacement of strings, and function calls when the parameter passing is the specific variables between the information transfer, formal parameters
As a local variable of a function, it is obviously memory-intensive.
5. Function calls are required to pay a certain amount of time and space overhead, because the system in the call function, to retain the scene, and then into the called function to execute, call the end,
Then return to the keynote function, and then restore the scene, these operations, obviously in the macro is not.
now look at the inline function:
The so-called "inline function" is a very simple function "embedded" into the call of his program code, only to do to avoid the 5th mentioned above, the purpose of
The time and space cost of the original function call is saved. But it must be noted that as an inline function, the function body must be very simple, can not contain cycles, conditions, selection
Complex structure, otherwise it can not be done as an inline function. In fact, even if you don't specify a function as an inline function, some compilation systems will automatically simplify
A single function is handled as an inline function, and for a complex function, even if you specify that he is an inline function, the system will ignore it.

Before introducing inline functions, it is necessary to introduce a preprocessing macro. Functions of inline functions and preprocessing macros
Features similar. I believe you have used preprocessing macros, we will often define a number of macros, such as
#define TABLE_COMP (x) (x) >0? ( x): 0)
A macro is defined.

Why do you use macros? Because the call to the function must move the order of the program execution to the function
An address stored in memory, after which the program contents of the function are executed, and then returned to the transfer to execute
The place before the function. This transfer operation requires that the site be saved and memory executed before being transferred to execution.
, return to the site, and continue to carry out the original save address. Therefore, a function call should have a
Fixed time and space costs, so it will affect its efficiency. And the macros are only in the pretreatment place
The code expands without additional space and time overhead, so calling a macro is more than calling a
Functions are more efficient.

   But macros also have a lot of undesirable places.
   1,. Macros cannot access private members of an object.
2,. The definition of a macro can easily produce two of meaning.
Let's give an example:
#define TABLE_MULTI (x) (x*x)
We use a number to call it, Table_multi (10), so it looks like nothing wrong,
The result returns 100, is correct, but if we use Table_multi (10+10) to call the words,
We expect the result to be 400, and the result of the macro invocation is (10+10*10+10), and the result is 120, which shows
It's not the result we're going to get. One way to avoid these errors is to add parentheses to the parameters of the macro.

#define TABLE_MULTI (x) ((x) * (x))

This ensures that there is no error, but even with this definition, the macro is still possible
An error, such as using Table_multi (a++) to invoke it, is intended to get (a+1) * (a+1)
Results, and actually? We can look at the expansion result of the macro: (a++) * (a++) If the value of a is
4, we get the result is 5*6=30. And the result we expect is 5*5=25, and there is a problem.
In fact, some of the library functions in C also have these problems. For example: Toupper (*pchar++) will
Pchar performs two + + operations, because ToUpper is actually a macro.

we can see that the macro has some unavoidable problems, how to solve it?

Here's how to solve these problems with the inline functions I want to introduce, we can use inline functions
To replace the definition of a macro. And in fact we can replace the preprocessing macros completely with inline functions.

The difference between an inline function and a macro is that the macro is replaced by the preprocessor, and the inline function is
implemented through compiler control. and inline functions are real functions, just when you need them.
The inline function expands like a macro, so it cancels the parameter stack of the function and reduces the call opening
Pin. You can invoke inline functions just as you would call a function without worrying about a
Some questions.
We can use inline to define inline functions, however, any letter defined in the description section of the class
Numbers are automatically considered to be inline functions.

   Let's introduce the use of inline functions.

Inline functions must be declared with the function body to be valid. A statement like this
Inline tablefunction (int I) is not effective, the compiler simply takes the function as an ordinary letter
Number statement, we must define the function body.

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

This allows us to define an inline function. We can tune it as a normal function.
Use. But the execution speed is faster than the normal function.

We can also define functions that are defined outside of the class as inline functions, such as:
Copy Code code 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;
}

The three functions stated above are inline functions. In C + +, the function body is defined within the class
function, which is implicitly considered an inline function. and whether or not you have inline keywords.

inline functions, which are most widely used in C + + classes, should be used to define access functions. We define the
A class typically defines a data member as private or protected so that the outside world cannot read and write directly to me.
The data of the members of our class.
Read-write for private or protected members must be performed using member interface functions. If we put
These read-write member functions are defined as inline functions, and are more efficient.
Copy Code code 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. Is that the execution code in the function is not too much, such as
The function body of the inline function is too large, and the general compiler will discard the inline method and use the normal method
Call the function. In this way, inline functions are as efficient as normal function execution.


use of macros
* This series of articles "C + + Tips" is the company Code Committee experts will be recommended by the engineer to see, feel good, take it out with the common improvement. Not
is to know how much will make a difference between people, the real difference is how much you can do.
Many programmers don't know what "macros" in C means. Especially when macros have parameters, macros and functions are often confused. I think here I'm still
First talk about "macros", a macro is just a definition, he defines a statement block, when the program is compiled, the compiler first to perform a "replace" the action of the source program
, replace the macro-defined statement block with the place where the macro is referenced, just like a text file replacement. This action term is called "expansion of macros". Using macros is a comparison of "crisis
Risk "Because you don't know what a macro will look like after it's expanded. 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 expands to become num1>num2?num1:num2;. However, as
The fruit is called by this, MAX (17+32, 25+21); , there are errors at compile time, because the macro expands and becomes: 17+32>25+21?17+32:25+21,
Woh, what is this?
So, when a macro is in use, the arguments must be in parentheses, and the example above can be solved by changing the examples shown below.
#define MAX ((a), (b)) (a) > (b)? (a) B)
Even so, no this macro still has bugs, because if I call MAX (i++,j++) like this; , after this macro, I and J have been added up to two
Times, this is by no means what we want. Therefore, the use of macros should be carefully considered, because the macro expansion is the result is difficult to predict. And although,
Macros execute quickly (because there is no overhead of a function call), but macros cause the source code to swell, making the target file size larger, (for example: a 50-line macro, program
1000 places to use, macro expansion will be very great), on the contrary can not let the program to perform faster (because the execution of the file is larger, the runtime system to change pages frequently
)。
Therefore, be careful when deciding whether to use a function or to use a macro.

The inline function definition in C + + is simple, as long as you add a keyword inline to the normal function, and there is nothing on the surface of the normal function.
What's the difference (including how the function is invoked), because so, in many C + + beginners (and even some people with C + + programming experience), inline only
is a concept, in fact, this is not a thorough understanding of the inline function, let's talk about inline functions and ordinary functions as well as the difference between the macro, phase
Letter After reading the following section, you must have a good understanding of these three.
The biggest difference between an inline function and a normal function is the internal implementation, not the surface form, and we know that when a normal function is called, the system
The first step is to jump to the entry address of the function, execute the function body, execute it, and then return to the function call where the function always has only one copy;
Inline functions do not require an addressing process, and when executed to an inline function, this function expands (very similar to the use of macros), if it is called at N
inline function, this function will have a copy of n pieces of code.
From the invocation of an inline function, it improves the execution efficiency of the code because of the lack of an addressing process, but this is in exchange for the cost of the space

A function that is declared inline, whose code snippet cannot be too long, is too long, and some compilers are considered ordinary functions (how long the function body exceeds the limit,
This seems to have no provisions, this is also really bad rules, the individual feel should be depending on the logic of the function body.
The following is an example of an inline function declaration:
inline void setval (int a) {m_b = a};
inline int getval () {return m_b};
As you can see from the example above, the declarations and implementations of inline functions are usually in one file (usually in. h).
Now let's talk about the difference between inline functions and macros. A lot of the data, when it comes to inline functions, is that inline functions are similar to macros, but classes
It seems to be similar, after all, we cannot use the two interchangeably.
The similarity between the two is that the compiler handles it when it executes, expands its code, and then continues with the following processing. The difference lies in macro
is a simple text substitution, it cannot return a value, there is no concept of general function parameters, and inline functions have the characteristics of ordinary functions, such as parameter list,
Return values, and so on. Here's an example to illustrate:
1. #define COUNT (x) (x * x)//A macro that calculates the product
2.inline int count (int x) {return x*x}//inline function to compute 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 be enough to illustrate the difference between the two, we will change the above example of the call to see the results

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 achieve the result of a product of 25, you should write this:
#define COUNT (x) ((x) * (x))
The example that corresponds to the 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.