1

To make a function inline should I add the keyword inline in function prototype or in function definition or should I add the inline keyword both in function declaration and function definition.

7
  • 1
    Note that the inline keyword is only a hint. The compiler is free to disregard it. And it's also free to compile functions not marked with inline as inline. Commented Jun 11, 2019 at 5:58
  • 1
    As for your problem, if all the compiler have is a declaration of a function, it often can't inline it no matter if you used the inline keyword or not. A definition (implementation) of the function is needed to be able to inline it. Commented Jun 11, 2019 at 5:59
  • @Someprogrammerdude does it make sense to use inline keyword to inline functions with a modern compiler? or should we let the compiler decide for us most of the time? Commented Jun 11, 2019 at 6:01
  • It doesn't hurt to add the keyword for definitions you feel are good candidates for inlining. Also note that member functions that are defined inside the class-definition are automatically inline, even if you don't add the keyword. Commented Jun 11, 2019 at 6:04
  • @Ayxan you don't have too much choice here. Commented Jun 11, 2019 at 6:05

2 Answers 2

5

If you already have a declaration and definition, you don't need to add inline anywhere. The inline keyword is not a magical optimization incantation, but more of a linkage specifier.

An inline function must be defined in every translation unit it's used in. How can it be defined there? Simple, it's put in header:

// foo.h inline void foo() {} 

But wait, I hear you say, won't putting it in header cause a multiple definitions error? Not when it's marked inline, that's why I called it more of a linkage specifier. The inline specifier tells the compiler that all those multiple definition it sees are the same. So it may in fact use any one of them. Or it may inspect the function body and choose to do code inlining, but it doesn't have to.

The primary purpose of the keyword is to allow those multiple definitions to appear inline, not to cause the function's code to be inlined. So again, if you have a definition in a cpp file and a declaration in a header, you don't need to do anything. If you have a utility you want to appear in a header, put it there - definition and all - and add the inline keyword.

Sign up to request clarification or add additional context in comments.

Comments

3

How to make function inline:

To make any function as inline, start its definitions with the keyword “inline”.

From the article.

2 Comments

can I omit the keyword inline in function declaration
No, but as @Some programmer dude mentioned, just mentioning the keyword inline doesn't make it inline as it depends on the function code if it includes iterations,recursion etc

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.