Thought Leadership

Staying in line

The idea of inlining code – placing the actual code of a small function at each call site – is a well known compiler optimization, which I have discussed before. This technique can provide significant performance improvements, due to the elimination of the call/return sequence. Also, stack usage is reduced. There is a possible cost in terms of increased program memory requirement.

It is reasonable to expect a good C or C++ compiler, when told to compile for speed, to perform inlining automatically. Some C compilers have extensions to give more control over this, but C++ has intrinsic support for inlining within the language …

C++ has a number of keywords that are additional to those in C. Among those is inline. This is a directive to the compiler requesting that the function is inlined. The compiler is at liberty to ignore the request, if the function is too big or inlining conflicts with optimization settings [i.e. if switches request small code instead of fast code]. The inline keyword is also implemented in many modern C compilers, as a language extension, and works in the same way.

But C++ has some other inlining tricks. It is very common for functions, which are part of objects [class member functions] to be small and called with great frequency. Thus, such functions are strong contenders for inlining. They may be declared inline in the same way, using the keyword. However, there is another way to convey the inlining request to the compiler: place the actual code inside the class definition, instead of just declaring the function and defining it outside.

So, C++ has two different ways to declare a function to be inline:

	class T1
	{
	public:
		void foo() 
		{
		}
	};

	class T2
	{
	public:
		void foo();
	};

	inline void T2::foo()
	{
	}

In this code, both classes have an inline function called foo().

This begs a question: what is the difference, in terms of generated code, between these two ways to declare an inline?
Please post answers as comments or by email. Sorry, there is no prize, but I will post the result as a comment in a week or so.

Colin Walls

I have over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, I am a member of the marketing team of the Mentor Graphics Embedded Systems Division, and am based in the UK. Away from work, I have a wide range of interests including photography and trying to point my two daughters in the right direction in life. Learn more about Colin, including his go-to karaoke song and the best parts of being British: http://go.mentor.com/3_acv

More from this author

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2010/02/22/staying-in-line/