The difference between macro, inline function and ordinary function

Source: Internet
Author: User

The execution of an inline function is similar to a parameter macro definition, but the parameters are handled differently. The macro definition with parameters does not operate on the parameter, but instead, the inline function is the function, which means that many properties of the function are applicable to the inline function, that is, the inline function evaluates the argument expression first, and then passes the value of the expression to the formal parameter.

Another difference between an inline function and a parameter macro definition is that the parameter type and the return value type of the inline function are explicitly specified in the declaration, whereas parameters with parameter macro definitions do not have the concept of a type, and only after the macro is expanded does the compiler check the syntax, which has many security implications.

When using inline functions, you should be aware of the following issues:
1) A definition declaration for an inline function should appear before the first call to the function.
2) inline functions are functions first, and many of the properties of functions apply to inline functions, such as inline functions that can be overloaded.
3) Loop Statements and switch results are not allowed in inline functions, and functions with exception-interface declarations cannot be declared as inline functions.

First say the difference between macros and functions:
1. The macro does a simple string substitution (note that the substitution of strings is not the substitution of other types of parameters), and the parameters of the function are passed, the parameters are
of the data type , and can be of various types.

2. The parameter substitution of a macro is handled directly without calculation, and the function call is to pass the value of the argument to the parameter, since it is a value that is calculated naturally.
3. Macro before compiling, that is, the macro body replace the macro name, and then compile, and the function is obviously compiled after the execution of the call. Therefore, the macro occupies
the compile time, and the function occupies the time of execution.

4. Macro parameters are not accounted for in memory space, because it is only to do the substitution of strings, and function calls when the parameter is passed between the specific variables of the information passing, formal parameters as a function of the local variables, obviously occupy memory.

5. Function call is to pay a certain time and space overhead, because the system in the call function, to keep the scene, and then into the called function to execute, call, and then return to the central function, at this time to restore the scene, these operations, obviously in the macro is not.


Now see inline functions:
The so-called "inline function" is a very simple function "inline" to invoke his program code, the only thing to do is to avoid the 5th, the purpose is to save the original function call time and space overhead. But it must be noted that as an inline function, the function body must be very simple and cannot contain loops, conditions, Select a complex structure, otherwise it cannot be an inline function. In fact, even if you do not specify a function as an inline function, some compiled systems will automatically handle a very simple function as an inline function, and for complex functions, even if you specify him as an inline function, the system will ignore it.

Before introducing inline functions, it is necessary to introduce pre-processing macros. The functions of inline functions are similar to the functions of preprocessing macros. I believe that we have used pre-processing macros, we will often define some macros, such as

#define TABLE_COMP (x) ((x) >0? ( x): 0)

A macro is defined.

Why use macros? Because a function call must transfer the execution order of the program to an address in memory of the function, the program content of the function is executed and then returned to the place before the function is transferred. This transfer operation requires the site to be saved and the address of the memory to be executed before it is transferred to the site, back to the scene, and continue with the original saved address. Therefore, function calls have a certain amount of time and space overhead, which will affect their efficiency. The macro simply expands the code where it is preprocessed and does not require additional space and time overhead, so calling a macro is more efficient than calling a function.

But the macro also has a lot of unsatisfactory places.

1,. Macros cannot access private members of an object.

2,. The definition of a macro is easy to 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 there is nothing wrong with the result, it returns 100, is correct, but if we use Table_multi (10+10) to call, we expect the result is 400, and the result of the macro call is (10+10 *10+10), the result is 120, which is obviously not the result we're going to get. One way to avoid these errors is to add parentheses to the macro parameters.

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

This ensures that there is no error, but even with this definition, the macro can still be faulted, such as using Table_multi (a++) to invoke it, and they want to get the result of (a+1) * (a+1), in fact? We can look at the macro expansion result: (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 that's a problem.

In fact, some of the library functions in C also have these problems. For example: Toupper (*pchar++) performs two + + operations on PChar because Toupper is actually a macro.

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

Here are some of the inline functions I'm going to cover to solve these problems, and we can use inline functions instead of the definition of macros. And in fact we can completely replace the preprocessing macros with inline functions.

The difference between an inline function and a macro is that a macro is replaced with a macro by a preprocessor, and inline functions are implemented through compiler control. and the inline function is the real function, but when needed, the inline function expands like a macro, so it cancels the function's argument stack and reduces the cost of the call. You can call inline functions just like you would call a function, without worrying about some of the problems that might arise from dealing with macros.

We can use inline to define inline functions, but any function defined in the Description section of the class is automatically considered an inline function.

Let's take a look at the use of inline functions.

The inline function must be declared together with the function body to be valid. A statement like this

Inline tablefunction (int I) is ineffective, and the compiler simply takes the function as a normal letter

Number declaration, we must define the function body.

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

So we can define an inline function. We can call it the same as a normal function. However, the execution speed is faster than the normal function.

We can also define functions that are defined outside the class as inline functions, such as:

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 declared above are inline functions. In C + +, the function body is defined inside a class.

function, which is implicitly considered an inline function. Regardless of whether you have the inline keyword.

Inline functions are most widely used in C + + classes and 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 the class.

You must use member interface functions to read and write to private or protected members. If we put

These read-write member functions are defined as inline functions, which will achieve better efficiency.

Class sample{

Private:

Int ntest;

Public:

Int Readtest () {return ntest;}

Void settest (int I) {ntest=i;}

}

Of course, the inline function also has some limitations. Is that the execution code in the function cannot be too many, such as

result, the function body of the inline function is too large, the general compiler will abandon the inline mode, and in the ordinary way

Call the function. In this way, the inline function is as efficient as the normal function execution.

Use of macros

/* This series of articles, "C + + Tips" is the company Code Committee experts will recommend engineers to see, feel good, take out with you to improve together. 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 "macro" means in C. In particular, macros and functions are often confused when macros have parameters. I want to be here, I'm still

Say "macro" first, the macro is just a definition, he defines a block of statements, when the program compiles, the compiler first to perform a "replace" the action of the source program

, replace the statement block defined by the macro with the one referenced by the macro, just as the text file is replaced. This action term is called "macro expansion". Using macros is a comparison of "dangerous

Because you don't know what the 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's no problem: MAX (NUM1, num2); Because the macro expands and becomes num1>num2?num1:num2;. However, as

The result is this invocation, MAX (17+32, 25+21); , the compile-time error occurs because the macro expands and becomes: 17+32>25+21?17+32:25+21,

Woh, what is this?

Therefore, the macro in use, the parameters must be enclosed in parentheses, the above example is changed to the following to solve the problem.

#define MAX ((a), (b)) (a) > (b)? (a) B)

Even if this is the case, there is still a bug in this macro, because if I call MAX (i++,j++) like this; , after this macro, I and J have been accumulated two times, this is not what we want. Therefore, the use of macros should be considered carefully, because the macro expansion is the result is very difficult to predict. And although, macro execution is very fast (because there is no cost of function calls), but the macro will let the source code to increase the size of the target file, (such as: a 50-line macro, the program has 1000 places to use, the macro will be very big after the expansion), instead of allowing the program to execute faster (because the execution Frequent page breaks at run time

)。

Therefore, be careful when deciding whether to use a function or 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 no difference on the surface of the normal function (including how the function is called), so that in many C + + beginners (and even some people with C + + programming experience) it seems that Inline is just a concept, in fact, this is not a thorough understanding of the internal function, the following we will talk about the inline function and the common function and the difference between the macro, I believe that after reading the following sections, you must have a good understanding of the three.

The biggest difference between an inline function and a normal function is the internal implementation aspect, not the surface form, we know that when the normal function is called, the system first jumps to the entry address of the function, executes the function body, executes, and then returns to the function call where the function always has only one copy; Inline functions do not require an addressing process, and when executed into an inline function, this function expands (much like the use of macros), and if this inline function is called at N, the function will have a copy of N code Snippets.

From the call 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 space.

A function declared as inline, its code snippet can not be too long, too long, some compilers are considered ordinary functions (how long the function body is more than the limit, this does not seem to be a rule, this is not a good rule, the individual think it should be seen as the logic of the function body).

The following is an example of a declaration of an inline function:
inline void setval (int a) {m_b = a};
inline int getval () {return m_b};
As can be seen from the above example, the Declaration and implementation of an inline function is usually in a file (usually in. h).
Let's talk about the difference between inline functions and macros. On a lot of data, when it comes to inline functions, it is said that inline functions are similar to macros, but similar, we cannot use them interchangeably.

The similarity between the two is that when the compiler handles it at execution time, its code is expanded, and the following processing continues after execution. The difference is that macro is a simple text substitution, it can not return a value, and there is no concept of general function parameters, while the inline function has the characteristics of ordinary functions, such as parameter list, return value, etc. Let's give 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 that calculates 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 be enough to explain the difference between the two, we change the invocation of the above example, and then look at the results

printf (COUNT (2+3)); 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, it should be written like this:
#define COUNT (x) ((x) * (x))
The example that corresponds to the above is #define COUNT (2+3) ((2+3) * (2+3))

The difference between macro, inline function and ordinary 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.