C ++ inline functions and macro definitions

Source: Internet
Author: User

Replacing macros with Inline:

1. inline debuggable;

2. You can perform type security check or automatic type conversion;

3. Accessible member variables.


In addition, the member functions defined in the class declaration are automatically converted to inline functions.

Article (1)

Inline functions and macro definitions
In C, a commonly used pre-processing statement # define is used to replace a function definition. For example:
# Define max (A, B) (a)> (B )? (A) (B ))
This statement makes every place in the program where the max (a, B) function is called by the expression (a)> (B) after the macro definition )? (A) (B) replace.

The writing format of macro-defined statements is overemphasized. There cannot be spaces between Max and parentheses. All parameters must be
In brackets. However, it is still troublesome:
Int A = 1, B = 0;
Max (A ++, B); // A is added twice
Max (A ++, B + 10); // A is added once
Max (a, "hello"); // compare int and string by mistake, no parameter type check
The evaluate of the max () function produces different side effects because the values of the two parameters are different.
The value of max (A ++, B) is 2, and the value of A is 3;
The value of max (A ++, B + 10) is 10, and the value of A is 2.
If it is a common function, max (a, "hello") will be checked by the function call, but this will not be rejected by compilation because the two parameter types are different. Fortunately, you can use an inline function to get the efficiency of replacing all macros, all foreseeable states, and check the type of common functions:
Inline int max (int A, int B)
{
Return A> B? A: B;
}

1. Differences between inline functions and macros:

Traditional macro-defined functions may cause some trouble.

Ex:

# Define f (x) x + x

Void main () {int I = 1; F (I ++ );}

Here, X will be added twice.

Inline functions are automatically added to the Code by the compiler when they are used.

The use of inline functions improves the efficiency (saving a lot of function call Assembly Code such as call and RET ).

2. Use of inline functions:

All functions defined in the class declaration will be automatically considered as inline functions.

Class ()

{

Void C (); // not a inline function;

Void D () {print ("d () is a inline function .");}

}

If you want to define a global function as an inline function available, the inline keyword.

Inline A () {print ("A () is a inline function .");}

Note:

Complex operations in inline functions are not inline. Such as loop and recursive call.

Summary:

Defining simple and short functions as inline functions improves efficiency.

Article (2)

8.5.1 replacing macro code with Inline
C ++ supports function inline to improve the function execution efficiency (speed ).
In
In the C program, macro code can be used to improve execution efficiency. Macro code itself is not a function, but it is used as a function. The pre-processor replaces function calls by copying macro code, eliminating the need for parameter pressure stacks and generating assembly language
Call call, return parameters, and execution of return operations increase the speed. The biggest disadvantage of using macro code is that it is prone to errors. The Preprocessor often produces unexpected marginal effects when copying macro code.
Yes. For example
# Define max (a, B) (a)> (B )? (A): (B)
Statement
Result = max (I, j) + 2;
Will be interpreted
Result = (I)> (j )? (I): (j) + 2;
Because the operator '+' has a higher priority than the operator ':', the preceding statement is not equivalent to the expected
Result = (I)> (j )? (I): (j) + 2;
If you rewrite the macro code
# Define max (A, B) (a)> (B )? (A): (B ))
It can solve the error caused by priority. However, the modified macro code is not foolproof, for example, the statement.
Result = max (I ++, J );
Will be interpreted
Result = (I ++)> (j )? (I ++): (j );
For C ++, the use of macro code has another drawback: The operation class of private data members is not allowed.

Let
Let's take a look at C ++
How "function inline" works. For any inline function, the compiler puts the declaration of the function (including the name, parameter type, and return value type) in the symbol table ). If no inline function is found in the compiler
The code of the function is also placed in the symbol table. When calling an inline function, the compiler first checks whether the call is correct (for type security checks, or for automatic type conversion, of course, for all functions
). If correct, the code of the inline function replaces the function call directly, saving the overhead of the function call. This process is significantly different from preprocessing because the pre-processor cannot perform type security checks.
Query, or perform automatic type conversion. If the inline function is a member function, the object address (this) will be placed in a suitable place, which is not implemented by the Preprocessor.
C ++
The function inline mechanism of languages not only improves the efficiency of macro code, but also increases the security. It also allows you to operate class data members freely. Therefore, in C ++
In the program, we should replace all macro code with inline functions. I am afraid "assert" is the only exception. Assert is a macro that only works in the debug version. It is used to check whether "should not" occur.
. In order not to cause any difference between the debug and release versions of the program, assert should not produce any side effects. If assert is a function, function calling will cause
Storage and code changes will lead to a difference between the debug version and the release version. So assert is not a function, but a macro. (See section 6.5 "using assertions ")
8.5.2 programming style of inline functions
The keyword inline must be put together with the function definition body to make the function inline. It does not work unless you put inline before the function declaration. The following function Foo cannot be an inline function:
Inline void Foo (int x, int y); // inline is only put together with the function declaration
Void Foo (int x, int y)
{
...
}
The following function Foo becomes an inline function:
Void Foo (int x, int y );
Inline void Foo (int x, int y) // put inline together with the function definition body
{
...
}
Institute
Inline is a keyword used for implementation, rather than a keyword used for declaration ". Generally, you can read the declaration of a function, but cannot see the definition of a function. Although in most
The Inline keyword is added before the declaration and definition body of inline functions in the textbook, but I don't think inline should appear in the declaration of functions. Although this detail does not affect function functions
A basic principle of high quality c ++/C programming style is introduced: Declarations and definitions cannot be confused, and users do not need or need to know whether functions need to be inline.
The member functions defined in the class declaration will automatically become inline functions, for example
Class
{
Public:
Void Foo (int x, int y ){... } // Automatically become an inline function
}
Putting the definition body of the member function in the class declaration can bring convenience in writing, but it is not a good programming style. The above example should be changed:
// Header file
Class
{
Public:
Void Foo (int x, int y );
}
// Definition file
Inline void a: Foo (int x, int y)
{
...
}

8.5.3 use inline with caution
Inner join can improve the execution efficiency of functions. Why not define all functions as inline functions?
If all functions are inline functions, do you still need the keyword "inline?
Internal
Association is at the cost of code expansion (replication). It only saves the overhead of function calls, thus improving the function execution efficiency. If the execution time of the Code in the function body is greater than the overhead of the function call, the efficiency
There will be little gains. On the other hand, every call to an inline function must copy the code, which will increase the total amount of code in the program and consume more memory space. Inline is not recommended in the following cases:
(1) If the code in the function body is long, using inline will cause high memory consumption.
(2) If there is a loop in the function body, the execution time of the Code in the function body is longer than the overhead of the function call.
Class constructor and destructor are easy to misunderstand that using inline is more effective. Be careful that constructors and destructor may hide some behaviors, such as secretly executing constructors and destructor of base classes or member objects. Therefore, do not place the constructor and destructor definitions in the class declaration.
A good compiler will automatically cancel the inline that is not worthwhile based on the definition body of the function (this further demonstrates that inline should not appear in the declaration of the function ).
8.6 experiences
C ++
The heavy load, inline, default parameters, and implicit conversion mechanisms in the language present many advantages, but these advantages are hidden. Just like people's diet, less food and overeating are not advisable, it should be just good
. We need to treat the new mechanisms of C ++ dialectically and use them appropriately. Although this will make us spend more time in programming, less time, but this is the art of programming.

Chapter 2 class constructor, destructor, and assignment function
Constructors, destructor, and assignment functions are the most basic functions of each class. They are so common that they are easy to paralyze. In fact, these seemingly simple functions are as dangerous as the sewers without the top cover.
Each class has only one destructor and one value assignment function, but it can have multiple Constructors (including one copy constructor, and others are called normal constructor ). If you do not want to write the above functions for any class A, the C ++ compiler will automatically generate four default functions for Class A, such
A (void); // default no-parameter Constructor
A (const A & A); // default copy constructor
~ A (void); // default destructor
A & operate = (const A & A); // default value assignment function

This is confusing. Why do programmers need to write functions automatically?
The reason is as follows:
(1) If "Default non-parametric constructor" and "Default destructor" are used, the chance of independent "initialization" and "Clearing" is abandoned, the good intentions of C ++ inventor stroustrup are in vain.
(2) Both the "Default copy constructor" and "Default Value assignment function" are implemented by "bit copy" instead of "value copy, if the class contains pointer variables, these two functions are doomed to go wrong.

For C ++ programmers who have not suffered enough, if he says it is easy to write constructor, destructor, and assignment function, he does not have to worry about it, indicating that his understanding is superficial, the level needs to be improved.
This chapter takes the design and implementation of the string class as an example to explain in depth the principles ignored by many textbooks. The string structure is as follows:
Class string
{
Public:
String (const char * STR = NULL); // common Constructor
String (const string & other); // copy the constructor
~ String (void); // destructor
String & operate = (const string & other); // value assignment function
PRIVATE:
Char * m_data; // used to save strings
};

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.