617

When should I write the keyword inline for a function/method in C++?

After seeing some answers, some related questions:

  • When should I not write the keyword 'inline' for a function/method in C++?

  • When will the compiler not know when to make a function/method 'inline'?

  • Does it matter if an application is multithreaded when one writes 'inline' for a function/method?

IAmInPLS
  • 3,648
  • 4
  • 22
  • 55
Partial
  • 8,263
  • 12
  • 39
  • 57

15 Answers15

981

Oh man, one of my pet peeves.

inline is more like static or extern than a directive telling the compiler to inline your functions. extern, static, inline are linkage directives, used almost exclusively by the linker, not the compiler.

It is said that inline hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.

  • static - the variable/function name cannot be used in other translation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another translation unit.

  • extern - use this variable/function name in this translation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.

  • inline - this function will be defined in multiple translation units, don't worry about it. The linker needs to make sure all translation units use a single instance of the variable/function.

Note: Generally, declaring templates inline is pointless, as they have the linkage semantics of inline already. However, explicit specialization and instantiation of templates require inline to be used.


Specific answers to your questions:

  • When should I write the keyword 'inline' for a function/method in C++?

    Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.

  • When should I not write the keyword 'inline' for a function/method in C++?

    Don't add inline just because you think your code will run faster if the compiler inlines it.

  • When will the compiler not know when to make a function/method 'inline'?

    Generally, the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all private methods are inlined whether you ask for it or not.

    As an aside to prevent inlining in GCC, use __attribute__(( noinline )), and in Visual Studio, use __declspec(noinline).

  • Does it matter if an application is multithreaded when one writes 'inline' for a function/method?

    Multithreading doesn't affect inlining in any way.

L. F.
  • 16,219
  • 7
  • 33
  • 67
deft_code
  • 51,579
  • 27
  • 135
  • 215
  • 203
    +1 Best description of inline I have seen in ... (forever). I will now rip you off and use this in all my explanations of the inline keyword. – Martin York Nov 19 '09 at 01:37
  • 1
    Does your answer to "When should I not write..." essentially mean, "if you think a function should be inline it shouldn't." Are your saying that we should inline one liners as a rule and not think too much about the rest? – Ziggy Aug 12 '11 at 18:25
  • 6
    @Ziggy, what I was trying to say was that compiler inlining and the `inline` keyword are not related. You've got the right idea though. As a rule, guessing what would would be improved by inlining is very error prone. The exception to that rule being one liners. – deft_code Aug 15 '11 at 18:50
  • 7
    This answer confuses me a bit. You say all that about the compiler being able to inline / not inline things better. Then you say that you should put one liners / small functions in the header, and that the compiler can't inline code without the function definition. Aren't these a bit contradictory? Why not just put everything in the cpp file and let the compiler decide? – user673679 Apr 03 '13 at 17:22
  • 8
    The compiler will only inline function calls where the definition is available at the call site. Leaving all function in the cpp file would limit inlining to that file. I suggest defining small one liners inline in the .h as the cost to compilation speed is negligible and you're almost guaranteed the compiler will inline the call. My point about compiler inlining is that it is port of the black art of optimization, at which your compiler is much better than you are. – deft_code Apr 03 '13 at 18:21
  • 1
    Is this answer still true? The idea that compilers pretty much do their own thing when inlining seems to fly in the face of the internet's cumulative knowledge. I like the idea of not inlining any more because of circular dependencies, but I won't tolerate losing performance. – Phlucious Apr 13 '13 at 01:22
  • 10
    Whenever I read something to the account of *the internet's cumulative knowledge* I have to think of John Lawton's famous quote: [The irony of the Information Age is that it has given new respectability to uninformed opinion.](http://www.goodreads.com/quotes/152506-the-irony-of-the-information-age-is-that-it-has) – IInspectable Sep 11 '13 at 17:58
  • Very nice answers but I still can't get how compiler will be able to inline a function if it doesn't see it's definition. Let's imagine we have main.cpp, func.cpp, func.h. In main we call `func()`. main.cpp is a separate compilation unit so it has no idea about func definition. Another situtation - what happens (yes, it's bad design) if class definition is divided into 2 separate files. Then how will private methods be inlined if compiler sees no their definition anymore? – sasha.sochka Sep 13 '13 at 15:08
  • "However, the compiler doesn't have the option to inline code if it doesn't have the function definition." Recent linker/compilier can do link time optimization and can inline function later if necessary. – Renaud Sep 17 '13 at 10:51
  • @deft_code: +1 for clarity in words, but what's confusing is that in the standard §7.1.2/3 footnote says `The inline keyword has no effect on the linkage of a function.`. Am I missing something here. – legends2k Oct 22 '13 at 13:05
  • 2
    @legends2k: linkage here is referring to a symbol can be used outside its compilation unit. This aspect of linking is controlled by `extern` (the default ... usually) and `static`. It is well defined to have a `static inline` or `extern inline` function. – deft_code Oct 22 '13 at 18:33
  • 1
    @Imray, it looks like the official term in the standard is "translation unit". I use the two interchangeably, but that may not be correct. see [What is a translation unit](http://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c) for more info. – deft_code Dec 16 '13 at 18:49
  • msvc also has __declspec(forceinline) – paulm Jan 02 '14 at 15:16
  • Your suggestion on using the 'inline' keyword seems over-complicated. I honestly feel like you could completely strip the inline keyword from the language and nothing would change. If you implement it in the header, the compiler will make the decision on its own; regardless of what you tell it. – void.pointer Feb 14 '14 at 20:28
  • 3
    @RobertDailey, C++ has no module support yet. The compiler for the most has no idea what a header is. When C++ gets good module support, you'll be correct that much(all?) of `inline`s semantics will not be needed. – deft_code Feb 19 '14 at 16:22
  • 1
    Also this answer seems a bit incorrect since section [7.1.2] in the C++03 standard states `"...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..."` So it's not just for scoping (even though I completely agree, the standard does make it pretty clear that it's more than that). – void.pointer May 13 '14 at 21:13
  • Ah, the pearls of C++ wisdom and mythology that very few will ever know. It's like the keyword was named `inline` solely to confuse the masses and keep the true meaning hidden for a select royal few. "Don't add inline when you think your code will run faster if the compiler inlines it." -- This was hilarious and very counter-intuitive, and also 100% correct :D – It's Your App LLC May 20 '14 at 03:53
  • 2
    So why do professionals use FORCEINLINE. As an example, UE4 source code has a lot of inline methods. Why do they let compiler do inlining? – Cahit Burak Küçüksütcü Oct 14 '14 at 10:37
  • 3
    @deft_code " It's a good idea to define small (as in one liner) functions in the header file" Modern compilers can use Link Time Opmization/Whole Program Optimization, when this is used defining a function in a header file makes no difference regarding inlining. – Étienne Jun 07 '15 at 18:27
  • 1
    @Etienne: Sure it does. Just because the linker can do inlining at lunchtime doesn't necessarily mean it will make the same decision, as the compiler would have. And btw.: GCC's inliner still does consider the inline keyword when making it's decision. It is not difficult to come up with an example, where versions with and without will result in different assembler code. – MikeMB Dec 05 '16 at 08:17
  • "the compiler doesn't have the option to inline code if it doesn't have the function definition", so if you want the compiler to have the option to inline, then you should put it in the header, which means it may be included by multiple compilation units, requiring you to use 'inline'. Alas, have we not come full circle by saying "use 'inline' to allow the compiler to inline"? (...or maybe I'm just missing it :)) – Droj Dec 30 '16 at 22:18
  • 4
    I have optimized several algorithms by simply adding "inline" where my profiler told me there was a bottle neck. I don't think that all compilers can always outperform human intervention. This answer is misleading and incomplete. Please refer to https://stackoverflow.com/questions/1932311/when-to-use-inline-function-and-when-not-to-use-it – Jean-Simon Brochu Jun 13 '17 at 13:51
  • 8
    "so most compilers flat out ignore the 'hint'." This is patently false. At least Clang and GCC use the inline keyword as a hint for inlining: https://blog.tartanllama.xyz/inline-hints/ – Jean-Michaël Celerier Mar 23 '18 at 12:52
  • 4
    LLVM will inline functions costing less than 225 or 325 if hinted. For scale a 7 case switch statement "costs" 110, devirtualization saves 100 cost. So hints do effect the compilers' inlining decisions and more than I thought (naively one would expect up to 50% more inlining if all functions were hinted). The intent of the ignore statement is to point out that the compiler inlines many functions w/o the hint and ignores complex hinted functions. I'll update the the comment to be more clear. – deft_code Jun 12 '18 at 21:12
  • I have a different observation. Using inline does make a difference across translation units. Example of two simple get functions in release mode with VS2017: the one with inline specifier gets inlined and the other is just a normal function call. Things become more obscure though using /LTCG or DLL module boundary. – gast128 Jan 28 '20 at 19:00
  • "only when the function's definition can show up in multiple translation units." is there any use case that you need this one ? – Trevor Feb 22 '20 at 12:37
  • 1
    @Trevor An important one in modern C++ is `constexpr`, which implies `inline`. The compiler can't evaluate a function without actually having it's definition, so you need it to be `inline` as every TU that uses it must have the definition. – HTNW May 30 '20 at 07:07
  • Why does the MS C++ docs https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp?view=vs-2019 say "The inline and __inline specifiers instruct the compiler to insert a copy of the function body into each place the function is called." if (now 20 years later), compilers ignore it? – 001001 Aug 12 '20 at 02:11
  • How did this answer get so many upvotes? It confused me more that I already was – FRR Aug 30 '20 at 03:13
  • @deft_code you said that __" you should use `inline` keyword when the function's definition can show up in multiple translation units__ and `Johannes Schaub - litb` said that in his answer(bottom of this page) __" If the function is declared in the header and defined in the .cpp file, you should not use the `inline` keyword."__ so I used `inline` keyword while declaring the function in `.h` header file and I define it in .cpp file but it give error such as `undefined reference` so I feel `johannes Schaub - litb` is correct but I am not sure so can you please put some light on this. – Abhishek Mane Apr 22 '21 at 12:55
75

I'd like to contribute to all of the great answers in this thread with a convincing example to disperse any remaining misunderstanding.

Given two source files, such as:

  • inline111.cpp:

    #include <iostream>
    
    void bar();
    
    inline int fun() {
      return 111;
    }
    
    int main() {
      std::cout << "inline111: fun() = " << fun() << ", &fun = " << (void*) &fun;
      bar();
    }
    
  • inline222.cpp:

    #include <iostream>
    
    inline int fun() {
      return 222;
    }
    
    void bar() {
      std::cout << "inline222: fun() = " << fun() << ", &fun = " << (void*) &fun;
    }
    

  • Case A:

    Compile:

    g++ -std=c++11 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x4029a0
    inline222: fun() = 111, &fun = 0x4029a0
    

    Discussion:

    1. Even thou you ought to have identical definitions of your inline functions, C++ compiler does not flag it if that is not the case (actually, due to separate compilation it has no ways to check it). It is your own duty to ensure this!

    2. Linker does not complain about One Definition Rule, as fun() is declared as inline. However, because inline111.cpp is the first translation unit (which actually calls fun()) processed by compiler, the compiler instantiates fun() upon its first call-encounter in inline111.cpp. If compiler decides not to expand fun() upon its call from anywhere else in your program (e.g. from inline222.cpp), the call to fun() will always be linked to its instance produced from inline111.cpp (the call to fun() inside inline222.cpp may also produce an instance in that translation unit, but it will remain unlinked). Indeed, that is evident from the identical &fun = 0x4029a0 print-outs.

    3. Finally, despite the inline suggestion to the compiler to actually expand the one-liner fun(), it ignores your suggestion completely, which is clear because fun() = 111 in both of the lines.


  • Case B:

    Compile (notice reverse order):

    g++ -std=c++11 inline222.cpp inline111.cpp
    

    Output:

    inline111: fun() = 222, &fun = 0x402980
    inline222: fun() = 222, &fun = 0x402980
    

    Discussion:

    1. This case asserts what have been discussed in Case A.

    2. Notice an important point, that if you comment out the actual call to fun() in inline222.cpp (e.g. comment out cout-statement in inline222.cpp completely) then, despite the compilation order of your translation units, fun() will be instantiated upon it's first call encounter in inline111.cpp, resulting in print-out for Case B as inline111: fun() = 111, &fun = 0x402980.


  • Case C:

    Compile (notice -O2):

    g++ -std=c++11 -O2 inline222.cpp inline111.cpp
    

    or

    g++ -std=c++11 -O2 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x402900
    inline222: fun() = 222, &fun = 0x402900
    

    Discussion:

    1. As is described here, -O2 optimization encourages compiler to actually expand the functions that can be inlined (Notice also that -fno-inline is default without optimization options). As is evident from the outprint here, the fun() has actually been inline expanded (according to its definition in that particular translation unit), resulting in two different fun() print-outs. Despite this, there is still only one globally linked instance of fun() (as required by the standard), as is evident from identical &fun print-out.
Jacob
  • 33,032
  • 14
  • 105
  • 160
Alaroff
  • 1,543
  • 11
  • 9
  • 14
    Your answer is an illustrative post of why language makes such `inline` functions to be undefined behavior. – R Sahu May 29 '18 at 15:50
  • You ought to also add cases where compiling and linking is separate, with each `.cpp` being its own translation unit. Preferably, add cases for `-flto` enabled/disabled. – syockit Nov 05 '19 at 04:29
  • 2
    The C++ reference explicitly sais "If an inline function or variable (since C++17) with external linkage is defined differently in different translation units, the behavior is undefined.". So the stuff you wrote is GCC specific as it is a side effect of orchestration of the compilation and linkage processes. Also, notice that this might vary between versions. – Petr Fiedler Feb 01 '20 at 01:29
  • I get that `inline` tells the linker to allow symbol collisions (sticking to the symbol from the first translation unit), but why on earth is it not required to test the symbols for equivalence? The standard should require compilers to provide LTO-information for all inline functions and make such checks mandatory! – Henrik Alsing Friberg Jun 25 '20 at 12:50
27

You still need to explicitly inline your function when doing template specialization (if specialization is in .h file)

BostonLogan
  • 1,531
  • 10
  • 12
21

1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.

2) Always. See #1.

(Edited to reflect that you broke your question into two questions...)

Aric TenEyck
  • 7,694
  • 32
  • 48
  • Yes. The inline is only a hint to the compiler, and it is free to ignore you. These days the compiler probably knows better than the programmer which functions are best to inline. – Mark Byers Nov 18 '09 at 21:51
  • 1
    Yes, but it's less relevant - for a function to be inlined, it's body must be in the same compilation unit (for instance, in a header). That's less common in C programs. – Michael Kohne Nov 18 '09 at 21:57
  • While the compiler can do a good job today, do you know of any cases when you should write it? – Partial Nov 18 '09 at 22:16
  • 1
    defining a non-member function template (aka non-static function template) does not require inline. See one definition rule(3.2/5). – deft_code Nov 18 '09 at 23:42
  • 4
    -1: `inline` is still needed, for example to _define_ a function in a header file (and that is required for inlining such a function in several compilation units). – Melebius Nov 18 '14 at 11:25
  • @Melebius : A function can be inlined in several compilation units without defining a function in a header file, and without using inline, the compiler has to be configured for that (In GCC this is called link time optimization, in visual studio whole program optimization). – Étienne Jun 07 '15 at 18:34
  • 2
    @Étienne that's implementation-specific. Per standard, there's One Definition Rule, which means here that if you naively include the function definition in multiple translation units, you'll get an error. But if that function has `inline` specifier, its instances are automagically collapsed into one by the linker, and ODR isn't used. – Ruslan Nov 22 '16 at 14:11
13

When should I not write the keyword 'inline' for a function/method in C++?

If the function is declared in the header and defined in the .cpp file, you should not write the keyword.

When will the the compiler not know when to make a function/method 'inline'?

There is no such situation. The compiler cannot make a function inline. All it can do is to inline some or all calls to the function. It can't do so if it hasn't got the code of the function (in that case the linker needs to do it if it is able to do so).

Does it matter if an application is multithreaded when one writes 'inline' for a function/method?

No, that does not matter at all.

Johannes Schaub - litb
  • 466,055
  • 116
  • 851
  • 1,175
  • There are cases where it is appropriate to use inline in a .cpp file. E.g. applying optimizations to code that is entirely implementation specific. – Robin Davies Apr 09 '20 at 01:18
  • @RobinDavies updated answer. It seems you misunderstood what I wanted to write. – Johannes Schaub - litb Apr 09 '20 at 11:55
  • @JohannesSchaub-litb __If the function is declared in the header and defined in the .cpp file, then you should not use the `inline` keyword.__ but `deft_code` (967 upvotes and Accepted answer) mention opposite to that __you should only use `inline` keyword when the function's definition can show up in multiple translation units__ so I checked it by declaring function in header file with keyword `inline` and defining it in .cpp file, it gives an error `undefined reference`. so you are right. Now also you mentioned,..........continue in next comment – Abhishek Mane Apr 22 '21 at 13:29
  • @JohannesSchaub-litb ........ __code of function in multiple translation unit is not available to compiler so it can't make them inline so it's linkers job__ . in this sense, `deft_code` says that __so you should use `inline` keyword so it gives compiler more info. to work with an optimizing code__ so his wording also makes sense here but when I try to use in code as mentioned early it gives error . so I feel both of your statements are opposite to each other but both of them makes sense but when I check practically your statements is true , so can you please put some light on this. – Abhishek Mane Apr 22 '21 at 13:31
5
  • When will the the compiler not know when to make a function/method 'inline'?

This depends on the compiler used. Do not blindly trust that nowadays compilers know better then humans how to inline and you should never use it for performance reasons, because it's linkage directive rather than optimization hint. While I agree that ideologically are these arguments correct encountering reality might be a different thing.

After reading multiple threads around I tried out of curiosity the effects of inline on the code I'm just working and the results were that I got measurable speedup for GCC and no speed up for Intel compiler.

(More detail: math simulations with few critical functions defined outside class, GCC 4.6.3 (g++ -O3), ICC 13.1.0 (icpc -O3); adding inline to critical points caused +6% speedup with GCC code).

So if you qualify GCC 4.6 as a modern compiler the result is that inline directive still matters if you write CPU intensive tasks and know where exactly is the bottleneck.

meda beda
  • 59
  • 1
  • 1
  • 6
    I'd like to see more evidence to back up your claims. Please provide code you are testing with as well as assembler output with and without inline keyword. Any number of things could have given you performance benefits. – void.pointer May 13 '14 at 20:59
  • 1
    Finally someone who doesn't only repeat what others say, but does actually verify those statements. Gcc does indeed still consider the inline keyword as a hint (I think clang ignores it completely). – MikeMB Dec 05 '16 at 08:21
  • @void.pointer: Why is this so hard to believe? If optimizers were perfect already, then new versions couldn't improve the program performance. But they regularly do. – MikeMB Dec 05 '16 at 08:23
3

In reality, pretty much never. All you're doing is suggesting that the compiler make a given function inline (e.g., replace all calls to this function /w its body). There are no guarantees, of course: the compiler may ignore the directive.

The compiler will generally do a good job of detecting + optimizing things like this.

DarkSquid
  • 2,638
  • 1
  • 20
  • 19
  • 8
    The problem is that `inline` has a _semantic_ difference in C++ (e.g. in the way multiple definitions are treated), which is important in some cases (e.g. templates). – Pavel Minaev Nov 18 '09 at 22:55
  • 4
    inline is used to resolve cases where a symbol has multiple definitions. Templates however are already handled by the language. One exception is a specialized template function that doesn't have any template paramters anymore (template<>). These are treated more like functions than templates and so need the inline keyword in order to link. – deft_code Nov 18 '09 at 23:47
2

gcc by default does not inline any functions when compiling without optimization enabled. I don't know about visual studio – deft_code

I checked this for Visual Studio 9 (15.00.30729.01) by compiling with /FAcs and looking at the assembly code: The compiler produced calls to member functions without optimization enabled in debug mode. Even if the function is marked with __forceinline, no inline runtime code is produced.

Jedzia
  • 104
  • 1
  • 4
  • 1
    Enable /Wall to be told about which functions where marked inline but didn't actually get inlined – paulm Jan 02 '14 at 15:17
0

Unless you are writing a library or have special reasons, you can forget about inline and use link-time optimization instead. It removes the requirement that a function definition must be in a header for it to be considered for inlining across compilation units, which is precisely what inline allows.

(But see Is there any reason why not to use link time optimization?)

Community
  • 1
  • 1
n.caillou
  • 1,090
  • 8
  • 15
0

C++ inline is totally different to C inline.

#include <iostream>
extern inline int i[];
int i [5];
struct c {
  int function (){return 1;} // implicitly inline
  static inline int j = 3; // explicitly inline
  static int k; // without inline, a static member has to be defined out of line
  static int f (){return 1;} // but a static method does not // implicitly inline
};

extern inline int b;
int b=3;
int c::k = 3; // when a static member is defined out of line it cannot have a static
              // specifier and if it doesn't have an `inline` specifier in the
              // declaration or on the definition then it is not inline and always
              // emits a strong global symbol in the translation unit

int main() {
  c j;
  std::cout << i;
}

inline on its own affects the compiler, assembler and the linker. It is a directive to the compiler saying only emit a symbol for this function/data if it's used in the translation unit, and if it is, then like class methods, tell the assembler to store them in the section .section .text.c::function(),"axG",@progbits,c::function(),comdat or .section .bss.i,"awG",@nobits,i,comdat for unitialised data or .section .data.b,"awG",@progbits,b,comdat for initialised data. Template instantiations also go in their own comdat groups.

This follows .section name, "flags"MG, @type, entsize, GroupName[, linkage]. For instance, the section name is .text.c::function(). axG means the section is allocatable, executable and in a group i.e. a group name will be specified (and there is no M flag so no entsize will be specified); @progbits means the section contains data and isn't blank; c::function() is the group name and the group has comdat linkage meaning that in all object files, all sections encountered with this group name tagged with comdat will be removed from the final executable except for 1 i.e. the compiler makes sure that there is only one definition in the translation unit and then tells the assembler to put it in its own group in the object file (1 section in 1 group) and then the linker will make sure that if any object files have a group with the same name, then only include one in the final .exe. The difference between inline and not using inline is now visible to the assembler and as a result the linker, because it's not stored in the regular .data or .text etc by the assembler due to their directives. Only inline symbols with external linkage are given external comdat linkage like this -- static linkage (local) symbols do not need to go in comdat groups.

inline on a non-static method declaration in a class makes the method inline if it is defined out-of-line, this will prevent the method being emitted in the translation unit if it is not referenced in the translation unit. The same effect is achieved by putting inline on the out-of-line definition. When a method is defined out-of-line without an inline specifier and the declaration in the class is not inline then it will emit a symbol for the method in the translation unit at all times because it will have external linkage rather than external comdat linkage. If the method is defined in the class then it is implicitly inline, which gives it external comdat linkage rather than external linkage.

static inline on a member in a class (as opposed to method) makes it a static member (which does not refer to its linkage -- it has the linkage of its class which may be extern). static inline also allows static members of the class to be defined inside the class instead of needing to be declared in the class and then defined out-of-line (without static in the definition, which wasn't allowed without -fpermissive). *static inline* also makes the members inline and not static inline -- inline means that the definition is only emitted if it is referenced in the translation unit. Previously you had to specify inline on the out-of-line definition to make the member inline.

Seeing as static methods can be defined in the class, static inline has no effect on the static method defined in the class, which always has external linkage, is a static method and is inline. If it is defined out of line then inline must be used to make it inline (i.e. to give to external comdat linkage rather than just external linkage), and static still can't be used.

static inline at file scope only affects the compiler. It means to the compiler: only emit a symbol for this function/data if it's used in the translation unit and do so as a regular static symbol (store in.text /.data without .globl directive). To the assembler there is now no difference between static and static inline. Like the other forms of inline, it cannot be used on a class, which is a type, but can be used on an object of the type of that class. This form of static inline also cannot be used on members or methods of a function, where it will always be treated inline as the static means something else in a class (it means that the class is acting as a scope rather than it being a member of or method to be used on an object).

extern inline is a declaration that means you must define this symbol in the translation unit if it is referenced or throw compiler error; if it's defined then treat it as a regular inline and to the assembler and linker there will be no difference between extern inline and inline, so this is a compiler guard only.

extern inline int i[];
extern int i[]; //allowed repetition of declaration with incomplete type, inherits inline property
extern int i[5]; //declaration now has complete type
extern int i[5]; //allowed redeclaration if it is the same complete type or has not yet been completed
extern int i[6]; //error, redeclaration with different complete type
int i[5]; //definition, must have complete type and same complete type as the declaration if there is a declaration with a complete type

The whole of the above without the error line collapses to inline int i[5]. Obviously if you did extern inline int i[] = {5}; then extern would be ignored due to the explicit definition through assignment.

I think the reason that static is not allowed on a static out-of-line definition without -fpermissive is because it implies that the static refers to static linkage, because it's not immediately obvious to the programmer that it is a member of a class or whether that class has , where the static means something different. -fpermissive ignores the static specifier on the out-of-line definition and it means nothing. In the case of a simple integer, k can't be defined out of a namespace, if c were a namespace, but if k were a function, then there would be no way of visibly telling from the line of code whether it is an out of line definition of a function in a namespace with static linkage, or an out-of-line definition of a static member with external linkage, and may give the wrong impression to the programmer / reader of the code.

For local classes, inline on a member / method will result in a compiler error and members and methods have no linkage.

For inline on a namespace, see this and this

Lewis Kelsey
  • 2,465
  • 1
  • 13
  • 21
-1

You want to put it in the very beginning, before return type. But most Compilers ignore it. If it's defined, and it has a smaller block of code, most compilers consider it inline anyway.

Jeremy Morgan
  • 3,205
  • 20
  • 22
-1

When developing and debugging code, leave inline out. It complicates debugging.

The major reason for adding them is to help optimize the generated code. Typically this trades increased code space for speed, but sometimes inline saves both code space and execution time.

Expending this kind of thought about performance optimization before algorithm completion is premature optimization.

wallyk
  • 53,902
  • 14
  • 79
  • 135
  • 12
    `inline` functions are typically not inlined unless compiling with optimizations, so they do not affect debugging in any way. Remember that it's a hint, not a demand. – Pavel Minaev Nov 18 '09 at 22:54
  • 3
    gcc by default does not inline any functions when compiling without optimization enabled. I don't know about visual studio – deft_code Nov 18 '09 at 23:07
  • I worked on an enormous g++ project which had debugging enabled. Maybe other options prevented it, but the `inline` functions were inlined. It was impossible to set a meaningful breakpoint in them. – wallyk Nov 18 '09 at 23:19
  • 2
    enabling debugging doesn't stop inlining in gcc. If any optimization where enabled (-O1 or greater), then gcc will try to inline the most obvious cases. Traditionally GDB has had a hard time with breakpoints and constructors especially inline constructors. But, that has been fixed in recent versions (at least 6.7, maybe sooner). – deft_code Nov 18 '09 at 23:51
  • 2
    Adding `inline` will do nothing to improve the code on a modern compiler, which can figure out whether to inline or not on its own. – David Thornley Nov 20 '09 at 22:22
-1

Inline keyword requests the compiler to replace the function call with the body of the function ,it first evaluates the expression and then passed.It reduces the function call overhead as there is no need to store the return address and stack memory is not required for function arguments.

When to use:

  • To Improve performance
  • To reduce call overhead .
  • As it's just a request to the compiler, certain functions won't be inlined *large functions
    • functions having too many conditional arguments
    • recursive code and code with loops etc.
Sheetal
  • 19
  • 2
  • 1
    It may benefit you to know that this isn't actually the case. The optimisation level -O0 through - Ofast is what determines whether a function is inlined or not. Inline on regular compilation (-O0) will not inline a function regardless of whether you use `inline` or not in C and C++. C Inline: https://stackoverflow.com/a/62287072/7194773 C++ inline: https://stackoverflow.com/a/62230963/7194773 – Lewis Kelsey Jun 09 '20 at 16:14
-2

When one should inline :

1.When one want to avoid overhead of things happening when function is called like parameter passing , control transfer, control return etc.

2.The function should be small,frequently called and making inline is really advantageous since as per 80-20 rule,try to make those function inline which has major impact on program performance.

As we know that inline is just a request to compiler similar to register and it will cost you at Object code size.

BenMorel
  • 30,280
  • 40
  • 163
  • 285
Ashish
  • 7,621
  • 11
  • 48
  • 89
  • "inline is just a request to compiler similar to register" They're similar because neither are requests or have anything to do with optimisation. `inline` has lost its status as an optimisation hint, and most compilers only use it to make allowances for multiple definitions - as IMO they should. More so, since C++11, `register` has fully been deprecated for its prior meaning of 'I know better than the compiler how to optimise': it's now just a reserved word with no current meaning. – underscore_d Oct 04 '16 at 20:20
  • @underscore_d: Gcc still listens to `inline` to some degree. – MikeMB Dec 05 '16 at 08:27
-2

C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.

To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.

A function definition in a class definition is an inline function definition, even without the use of the inline specifier.

Following is an example, which makes use of inline function to return max of two numbers

#include <iostream>

using namespace std;

inline int Max(int x, int y) { return (x > y)? x : y; }

// Main function for the program
int main() {
   cout << "Max (100,1010): " << Max(100,1010) << endl;

   return 0;
}

for more information see here.

amirfg
  • 166
  • 1
  • 4
  • 18