Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ inline function?

Tags:

c++

inline

Why should i do something like this:

inline double square (double x) { return x*x;} 

instead of

double square (double x) { return x*x;} 

Is there a difference?

like image 351
Pwnna Avatar asked May 11 '11 23:05

Pwnna


People also ask

What is an inline C function?

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.

Does C has inline function?

Standard support. C++ and C99, but not its predecessors K&R C and C89, have support for inline functions, though with different semantics. In both cases, inline does not force inlining; the compiler is free to choose not to inline the function at all, or only in some cases.

What is __ inline in C?

The inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. Using inline functions can make your program faster because they eliminate the overhead associated with function calls.

What is difference between inline function and normal function in C?

Functions that are present inside a class are implicitly inline. Functions that are present outside class are considered normal functions.


2 Answers

The former (using inline) allows you to put that function in a header file, where it can be included in multiple source files. Using inline makes the identifier in file scope, much like declaring it static. Without using inline, you would get a multiple symbol definition error from the linker.

Of course, this is in addition to the hint to the compiler that the function should be compiled inline into where it is used (avoiding a function call overhead). The compiler is not required to act upon the inline hint.

like image 61
Greg Hewgill Avatar answered Oct 11 '22 13:10

Greg Hewgill


On a modern compiler there is likely not much difference. It may be inlined without the inline and it may not be inlined with the inline.

like image 37
Ben Jackson Avatar answered Oct 11 '22 13:10

Ben Jackson