Friday, June 25, 2010

Inline functions in C++, finding out with g++

Hi,
In C++, if I define a function body inside a class, rather than
outside, compiler is supposed to treat it as an inline function.
How do I find out whether the compiler has actually done that?
In general , how do I find out whether the compiler treats a particular
function as inline or not, by looking at the output generated by
the compiler?

I am using g++.


Ans :
When I try this compiler, I get the same results you displayed when
optimization is not used.

Try compiling with the following command line options:
g++ -S main.cpp -O3

Even if you optimize it to level 1 (-O1) you'll notice the code gets inline.

You'll also notice that the code gets more compact when you use the
inline keyword.

I tested this with the version of the code I previously posted, which
does not use cout.
By removing any additional library and header requirements to the
code, it makes it easier to see assembly code related to inline logic.

class salesman{

int salesman_no;
char name[25];
int product_no;
public :
salesman(int salesman, int product):salesman_no(salesman),
product_no(product)
{
}

inline int readData(){
return product_no;
}

inline int check();
};

int salesman::check(){
return salesman_no;
}

int main(int argc, char *argv[])
{
salesman man1(4, 5);
int v1 = man1.readData(); //Don't use cout
int v2 = man1.check(); //Use int, so as to remove
additional assembly code

return 0;
}

No comments:

Blog Archive