C++ inline function and constexpr function

Inline function (inline)

First define an inline function ShorterString to compare the lengths of two string parameters and return the one with the smaller length.

inline  ShorterString(const string &s1, const string &s2){
    
    
	return s1.size() <= s2.size() ? s1:s2;
}

The benefits of defining a function for such a small operation are:

① It is much easier to read and understand the call of the function max than to read an equivalent conditional expression and explain its meaning ②
If any modification is required, it is easier to modify the function than to find and modify every equivalent expression Much easier
③ Using functions ensures uniform behavior, each test is guaranteed to be implemented in the same way
④ Functions can be reused without having to rewrite code for other applications

Key points:
1. The keyword inline must be put together with the function definition body to make the function inline. Just putting inline in front of the function declaration has no effect.

2. Designate the function as an "inline function (inline)" and "expand it inline" at each call point. This description is just a request to the compiler, and the compiler can choose to ignore this request. The inline mechanism is used to optimize small-scale, direct-flow, and frequently-called functions. It is recommended that the number should not exceed 75 lines.

constexpr function

constexpr is a new keyword in C++11, and its semantics is "constant expression", that is, an expression that can be evaluated at compile time. The most basic constant expression is a literal value or the address of a global variable/function or the result returned by keywords such as sizeof, while other constant expressions are obtained from basic expressions through various definite operations. Constexpr values ​​can be used in enum, switch, array length, etc.

constexpr int Inc(int i) {
    
    

    return i + 1;

}

constexpr int a = Inc(1);

constexpr int b = Inc(cin.get());

constexpr int c = a * 2 + 1;

Benefits of constexpr:

It is a strong constraint, which better guarantees that the correct semantics of the program will not be destroyed.
The compiler can greatly optimize the constexpr code during compilation, such as directly replacing the used constexpr expressions with the final result.
Compared with macros, there is no additional overhead, but it is safer and more reliable.

Guess you like

Origin blog.csdn.net/Algabeno/article/details/123554569