You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
helpviewer_keywords: ["inline functions [C++], class members"]
7
-
ms.assetid: 355f120c-2847-4608-ac04-8dda18ffe10c
8
7
---
9
8
# Inline functions (C++)
10
9
11
-
The **`inline`** keyword tells the compiler to substitute the code within the function definition for every instance of a function call.
10
+
The **`inline`** keyword suggests that the compiler substitute the code within the function definition for every instance of a function call.
12
11
13
-
Using inline functions can make your program faster because they eliminate the overhead associated with function calls. The compiler can optimize functions expanded inline in ways that aren't available to normal functions.
12
+
In theory, using inline functions can make your program faster because they eliminate the overhead associated with function calls. Calling a function requires pushing the return address on the stack, pushing arguments onto the stack, jumping to the function body, and then executing a return instruction when the function finishes. This process is eliminated by inlining the function. The compiler can optimize functions expanded inline in ways that aren't available for a normal functions. A tradeoff is that the overall size of your program can increase.
14
13
15
-
Inline code substitution occurs at the compiler's discretion. For example, the compiler won't inline a function if its address is taken or if it's too large to inline.
14
+
Inline code substitution occurs at the compiler's discretion. For example, the compiler won't inline a function if its address is taken or if the compiler decides it is too large to be practical to inline.
16
15
17
16
A function defined in the body of a class declaration is implicitly an inline function.
18
17
19
18
## Example
20
19
21
-
In the following class declaration, the `Account` constructor is an inline function. The member functions `GetBalance`, `Deposit`, and `Withdraw`aren't specified as **`inline`** but can be implemented as inline functions.
20
+
In the following class declaration, the `Account` constructor is an inline function because it is defined in the body of the class declaration. The member functions `GetBalance`, `Deposit`, and `Withdraw`are specified `inline` in their definitions. The `inline` keyword is optional in the function declarations in the class declaration.
> In the class declaration, the functions were declared without the **`inline`** keyword. The **`inline`** keyword can be specified in the class declaration; the result is the same.
57
57
58
-
A given inline member function must be declared the same way in every compilation unit. This constraint causes inline functions to behave as if they were instantiated functions. Additionally, there must be exactly one definition of an inline function.
58
+
A given inline member function must be declared the same way in every compilation unit. There must be exactly one definition of an inline function.
59
59
60
-
A class member function defaults to external linkage unless a definition for that function contains the **`inline`** specifier. The preceding example shows that you don't have to declare these functions explicitly with the **`inline`** specifier. Using **`inline`** in the function definition causes it to be an inline function. However, you can't redeclare a function as **`inline`** after a call to that function.
60
+
A class member function defaults to external linkage unless a definition for that function contains the **`inline`** specifier. The preceding example shows that you don't have to declare these functions explicitly with the **`inline`** specifier. Using **`inline`** in the function definition suggests to the compiler that it be treated as an inline function. However, you can't redeclare a function as **`inline`** after a call to that function.
61
61
62
62
## `inline`, `__inline`, and `__forceinline`
63
63
64
-
The **`inline`** and **`__inline`** specifiers instruct the compiler to insert a copy of the function body into each place the function is called.
64
+
The **`inline`** and **`__inline`** specifiers suggest to the compiler that it insert a copy of the function body into each place the function is called.
65
65
66
-
The insertion, called *inline expansion* or *inlining*, occurs only if the compiler's cost-benefit analysis shows it's worthwhile. Inline expansion minimizes the function-call overhead at the potential cost of larger code size.
66
+
The insertion, called *inline expansion* or *inlining*, occurs only if the compiler's own cost-benefit analysis shows it's worthwhile. Inline expansion minimizes the function-call overhead at the potential cost of larger code size.
67
67
68
68
The **`__forceinline`** keyword overrides the cost-benefit analysis and relies on the judgment of the programmer instead. Exercise caution when using **`__forceinline`**. Indiscriminate use of **`__forceinline`** can result in larger code with only marginal performance gains or, in some cases, even performance losses (because of the increased paging of a larger executable, for example).
69
69
70
70
The compiler treats the inline expansion options and keywords as suggestions. There's no guarantee that functions will be inlined. You can't force the compiler to inline a particular function, even with the **`__forceinline`** keyword. When you compile with **`/clr`**, the compiler won't inline a function if there are security attributes applied to the function.
71
71
72
72
For compatibility with previous versions, **`_inline`** and **`_forceinline`** are synonyms for **`__inline`** and **`__forceinline`**, respectively, unless compiler option [`/Za` \(Disable language extensions)](../build/reference/za-ze-disable-language-extensions.md) is specified.
73
73
74
-
The **`inline`** keyword tells the compiler that inline expansion is preferred. However, the compiler can create a separate instance of the function (instantiate) and create standard calling linkages instead of inserting the code inline. Two cases where this behavior can happen are:
74
+
The **`inline`** keyword tells the compiler that inline expansion is preferred. However, the compiler can ignore this. Two cases where this behavior can happen are:
75
75
76
76
- Recursive functions.
77
-
78
77
- Functions that are referred to through a pointer elsewhere in the translation unit.
79
78
80
-
These reasons may interfere with inlining, *as may others*, at the discretion of the compiler; you shouldn't depend on the **`inline`** specifier to cause a function to be inlined.
79
+
These reasons may interfere with inlining, *as may others*, at the discretion of the compiler. Don't depend on the **`inline`** specifier to cause a function to be inlined.
81
80
82
81
Rather than expand an inline function defined in a header file, the compiler may create it as a callable function in more than one translation unit. The compiler marks the generated function for the linker to prevent one-definition-rule (ODR) violations.
83
82
84
83
As with normal functions, there's no defined order for argument evaluation in an inline function. In fact, it could be different from the argument evaluation order when passed using the normal function-call protocol.
85
84
86
-
The [`/Ob`](../build/reference/ob-inline-function-expansion.md) compiler optimization option helps to determine whether inline function expansion actually occurs.
87
-
85
+
The [`/Ob`](../build/reference/ob-inline-function-expansion.md) compiler optimization option helps to determine whether inline function expansion actually occurs.\
88
86
[`/LTCG`](../build/reference/ltcg-link-time-code-generation.md) does cross-module inlining whether it's requested in source code or not.
89
87
90
88
### Example 1
@@ -121,28 +119,20 @@ private:
121
119
122
120
The **`__inline`** keyword is equivalent to **`inline`**.
123
121
124
-
Even with **`__forceinline`**, the compiler can't inline code in all circumstances. The compiler can't inline a function if:
122
+
Even with **`__forceinline`**, the compiler can't inline a function if:
125
123
126
124
- The function or its caller is compiled with **`/Ob0`** (the default option for debug builds).
127
-
128
125
- The function and the caller use different types of exception handling (C++ exception handling in one, structured exception handling in the other).
129
-
130
126
- The function has a variable argument list.
131
-
132
127
- The function uses inline assembly, unless compiled with **`/Ox`**, **`/O1`**, or **`/O2`**.
133
-
134
128
- The function is recursive and doesn't have **`#pragma inline_recursion(on)`** set. With the pragma, recursive functions are inlined to a default depth of 16 calls. To reduce the inlining depth, use [`inline_depth`](../preprocessor/inline-depth.md) pragma.
135
-
136
129
- The function is virtual and is called virtually. Direct calls to virtual functions can be inlined.
137
-
138
130
- The program takes the address of the function and the call is made via the pointer to the function. Direct calls to functions that have had their address taken can be inlined.
139
-
140
131
- The function is also marked with the [`naked`](../cpp/naked-cpp.md) [`__declspec`](../cpp/declspec.md) modifier.
141
132
142
133
If the compiler can't inline a function declared with **`__forceinline`**, it generates a level 1 warning, except when:
143
134
144
135
- The function is compiled by using /Od or /Ob0. No inlining is expected in these cases.
145
-
146
136
- The function is defined externally, in an included library or another translation unit, or is a virtual call target or indirect call target. The compiler can't identify non-inlined code that it can't find in the current translation unit.
147
137
148
138
Recursive functions can be replaced with inline code to a depth specified by the [`inline_depth`](../preprocessor/inline-depth.md) pragma, up to a maximum of 16 calls. After that depth, recursive function calls are treated as calls to an instance of the function. The depth to which recursive functions are examined by the inline heuristic can't exceed 16. The [`inline_recursion`](../preprocessor/inline-recursion.md) pragma controls the inline expansion of a function currently under expansion. See the [Inline-Function Expansion](../build/reference/ob-inline-function-expansion.md) (/Ob) compiler option for related information.
@@ -152,12 +142,11 @@ Recursive functions can be replaced with inline code to a depth specified by the
152
142
For more information on using the **`inline`** specifier, see:
153
143
154
144
- [Inline Class Member Functions](../cpp/inline-functions-cpp.md)
155
-
156
145
- [Defining Inline C++ Functions with dllexport and dllimport](../cpp/defining-inline-cpp-functions-with-dllexport-and-dllimport.md)
157
146
158
147
## When to use inline functions
159
148
160
-
Inline functions are best used for small functions such as accessing private data members. The main purpose of these one- or two-line "accessor" functions is to return state information about objects. Short functions are sensitive to the overhead of function calls. Longer functions spend proportionately less time in the calling and returning sequence and benefit less from inlining.
149
+
Inline functions are best used for small functions such as accessing private data members. The main purpose of these one- or two-line accessor functions is to return state information about objects. Short functions are sensitive to the overhead of function calls. Longer functions spend proportionately less time in the calling and returning sequence and benefit less from inlining.
161
150
162
151
A `Point` class can be defined as follows:
163
152
@@ -191,20 +180,62 @@ int main()
191
180
Assuming coordinate manipulation is a relatively common operation in a client of such a class, specifying the two accessor functions (`x` and `y` in the preceding example) as **`inline`** typically saves the overhead on:
192
181
193
182
- Function calls (including parameter passing and placing the object's address on the stack)
194
-
195
183
- Preservation of caller's stack frame
196
-
197
184
- New stack frame setup
198
-
199
185
- Return-value communication
200
-
201
186
- Restoring the old stack frame
202
-
203
187
- Return
204
188
205
189
## Inline functions vs. macros
206
190
207
-
inline functions are parsed by the compiler, and macros are expanded by the preprocessor.
191
+
A macro may seem to have some of the properties of an `inline` function. But there are important differences. Consider the following example:
std::cout << mult(2, 2.2) << std::endl>>; // no warning
209
+
std::cout << multiply(2, 2.2); // Warning C4244 'argument': conversion from 'double' to 'int', possible loss of data
210
+
}
211
+
```
212
+
213
+
```Output
214
+
35
215
+
100
216
+
4.4
217
+
4
218
+
```
219
+
220
+
Here are some of the differences between the macro and the inline function:
221
+
222
+
- Macros are always expanded inline. However, an inline function is only inlined when the compiler determines it is the optimal thing to do.
223
+
- The macro may result in unexpected behavior. For example, the macro `mult(5+5,5+5)` expands to `5 + 5 * 5 + 5` resulting in 35, whereas the function evaluates `10 * 10`.
224
+
- An inline function is subject to semantic processing by the compiler, whereas the expansion of a macro is done by the preprocessor and doesn't benefit from the same semantic processing. Thus, macros aren't type-safe, whereas functions are.
225
+
- Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once. For example, consider the following:
226
+
227
+
```cpp
228
+
#definesqr(a) a * a
229
+
230
+
intmain()
231
+
{
232
+
int c = 5;
233
+
std::cout << sqr(c++) << std::endl; // outputs 25
234
+
std::cout << c << std::endl; // outputs 7!
235
+
}
236
+
```
237
+
238
+
In this example, the expression `c++` is evaluated twice, once for each occurrence of `a` in the macro expansion. Instead, if `sqr` were an inline function, the expression `c++` would be evaluated only once.
0 commit comments