开发者

C: Is the inline keyword worth it?

开发者 https://www.devze.com 2023-01-14 19:18 出处:网络
Is it worth it to use the inline keyword or the compiler is smart enough to 开发者_StackOverflowknow when he needs to inline a function ?Yes, it is smart enough.But what has made no progress at all in

Is it worth it to use the inline keyword or the compiler is smart enough to 开发者_StackOverflowknow when he needs to inline a function ?


Yes, it is smart enough. But what has made no progress at all in the past 40 years is the way C programs are built. It is still one source code file at a time.

So to get a function inlined in more then one .c file you put the function definition in the .h file. And if you don't mark them inline, the linker will complain about the multiple definitions.


The compiler is pretty smart, and has multiple metrics to figure out if something is worth inlining. But sometimes however the developer will have knowledge about how the application is going to be run and will know to inline something that the compiler doesn't do automatically. However, I would never inline stuff manually unless I had a done some benchmarks and found that inline would improve my performance.

You can read more about how GCC uses inline.


Its always worth being explicit about intention.

Its also worth noting that the compiler doesn't even need to inline if it thinks its better not too.


The Standard says

7.1.2 Function specifiers

2. A function declaration (8.3.5, 9.3, 11.4) 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; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

So I'd liken inline to maybe <br /> in HTML -- it is good practice to use the self-closing <br /> all the time. But one might argue that almost all browser implementations treat <br> and <br /> exactly the same, which IMO misses the point.

As others have noted, this is probably not very relevant for performance value in these days. But I think it still serves nicely as a semantic, intention conveying keyword.

0

精彩评论

暂无评论...
验证码 换一张
取 消