Reputation: 41
I'm a newbie programmer. There are these line in our text book, sumitha arora class 12 ix edition:
The inlining does not work for the following situations:
For functions that return values and are having a loop or switch or goto.
For functions not returning values, if a return statement exists.
If 1 and 2 are true then how are inline functions possible to create?
P.S. the lines are exactly the same from the book no alterations
Upvotes: 3
Views: 10084
Reputation: 13690
I don't know what compiler is referred in the book. In general it will depend on the actual compiler, what can be inlined or when a function body will be generated.
The statements doesn't exclude each other as you might assume. The general condition to inhihbit inline is a branch in the function except a simple if statement. The branches in (1) are the loops and the goto
. The branch in (2) is the jump to the end of the function on return;
Edit:
It is highly dependent on the compiler. Nested if
might work. But switch
statements differs, as they are often implemented with a jump table instead of several if
statements. The jump table includes location similar to the goto
labels. That might be more difficult for the actual compiler. Therefore it might be sensible to make a distinction.
Upvotes: 2
Reputation: 9406
IMHO, the C++ standard does not define restrictions for inlining. Inline functions are defined in section 7.1.2.2:
A function declaration with an inline specifier declares an inline function . The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call;
Compilers usually have some heuristics to decide if a function will be inlined or not. This balances the cost to perform an actual function call (push arguments on the stack, jump etc) with the effects of having a larger function (the most obvious drawback is an increased size of the resulting binary), but the concrete rules are left open for the compiler implementer.
If the book is not talking about a specific compiler, I see not reason why this statement is true in general. It may a rule of thumb, though.
Upvotes: 0
Reputation: 5359
Inline functions are basically written when the code is small and the stack push/pop takes up much of the overhead. What they do is, they expand the function where they are written. Since there is no push/pop associated, you cannot expect value to be returned. Although, C++ can convert simple functions with only a return statement to inline functions.
Here's a C++ code:
inline int max(int a, int b)
{
return (a > b) ? a : b;
}
Then, a statement such as the following:
a = max(x, y);
may be transformed into a more direct computation:
a = (x > y) ? x : y;
Upvotes: 1