Rupesh Bhandari
Rupesh Bhandari

Reputation: 86

Will compiler ignore inline qualifier for my function?

I read that having more than a line in a function will falsify "inline", if so how do i get to know when my function is inlined and vice-versa :/

inline int foo(int x, int y)
{
   cout<<"foo-boo";
   return (x > y)? x : y;
}

Upvotes: 2

Views: 2553

Answers (2)

Sathya
Sathya

Reputation: 195

Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlining in such circumstances like:

  1. If a function contains a loop. (for, while, do-while)
  2. If a function contains static variables.
  3. If a function is recursive.
  4. If a function return type is other than void, and the return statement doesn’t exist in function body.
  5. If a function contains switch or goto statement.

Upvotes: 11

cadaniluk
cadaniluk

Reputation: 15229

inline is in no way related to the number of lines in a function1. It is just a compiler hint, which the compiler is not, by any means, obliged to follow. Whether a function is really inlined when declared inline, is implementation-defined.
From C++14 standard draft N3690, §7.1.2:

A function declaration (8.3.5, 9.3, 11.3) 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 [...]

(Formatting mine.)

There are compiler-specific options and attributes to enable/disable inlining for all functions and do other, related stuff. Look up your compiler's documentation for further information.


1 A compiler could take the line count of a function into account when deciding on whether to inline a function or not but that's implementation-defined and not required by the standard.

Upvotes: 2

Related Questions