Hacker News new | ask | show | jobs
by kgabis 4695 days ago
Why does that keyword even exist then?
4 comments

The primary effect of the inline keyword is to tell the compiler that a function is not to be exported from the current object. e.g.

foo.h:

int bar(int i) { return i; /* awesome function! */

foo.cpp: #include "foo.h" … bar(5) …

At this point everything is fine, but lets say there's also:

wiffle.cpp: #include "foo.h" … bar(6) …

now both foo.o and bar.o will contain a function named bar - because they picked up the definition in foo.h and c/c++ don't (technically) see any difference between a function that has been written inline, or a function that was included from a header.

By slapping the inline keyword on the function bar, the link flags for the function change so that the bar won't be exported from any object file that includes it, and so the name collision will no longer occur at link time.

There are a bunch of other benefits, mostly along the lines of "there function doesn't need to be exported therefore if it's not used i don't need to include it in the object"

It allows multiple (equivalent) definitions from different translation units to coexist in the same program. That's the only actual meaning attached to it by the standard.
Try putting this in an .h file that you include in several places:

void hi() { int x = 3; }

without the inline and you will get a complaint that hi() is multiply defined at link time. So, one use case.

Because some compilers do make use of that hint in useful ways. They're just not required to, nor are they required to do so in any specific situation, much like the register and volatile keywords.
volatile is not a hint, it's a requirement. You couldn't control hardware without it (compiler: "you're only writing this variable, never reading it. I'll skip those writes to speed things up". Programmer: "why isn't my program writing anything to this I/O port?")
I suggest reading the C standard, where you'll find that, despite the many words used about volatile, it doesn't really guarantee you anything at all. I especially love this sentence:

> "What constitutes an access to an object that has volatile-qualified type is implementation-defined."

The behavior of I/O ports and the meaning of any attempt to access them is beyond the scope of the standards. The "requirements" that exist for volatile are simply an absurdity outside the (new in C11/C++11) threading context, since the implementation is not actually required to do anything useful.