Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Ask experience of inline in C++?

Author: Sven Reichard

Date: 09:54:38 05/08/01

Go up one level in this thread


On May 08, 2001 at 00:36:09, Pham Minh Tri wrote:

>Hi,
>
>I write my chess program in C++ (compile by VC6.0). To speed up, I have managed
>to use as many inlines (both implicit and explicit) as posible. Many pieces of
>code have the following form:
>
>class abc {
>  void A(int x) { do something. There are 100 places use x; }
>  void B() { A(exp); }
>};
>
>(When I call function B, it calls function A with parameter of a short
>expression).
>
>Now I am wondering that compiler may embed directly the expression of parameter
>from function B into A, it means instead of calling that expression one time and
>use its results 100 times, now I may waste time by calling it 100 times!!!
>
>Does anyone has experience about this problem? What exactly the compiler (Visual
>C 6.0) do for this case? (Don't tell your guess, plz).
>

According to the standard and common sense, inlined functions must have the same
effect as non-inlined ones. Thus

inline void A(int x)
{
  f1(x); f2(x); f3(x);
};
void B()
{
  A(g(x));
};

has to expand to
void B()
{
  int tmp(g(x));
  f1(tmp); f2(tmp); f3(tmp);
};

and that is what VC or g++ do.

Just assume, g(x) (or exp) have some side effects, then it would make a
difference if it is called once or several times. If g(x) were called several
times, that would invalidate the results.

One thing to be careful about is macro definitions; if instead of the inline
function above you write something like

# define A(x) { f1(x); f2(x); f3(x);}

then A(g(x)) actually calls g three times. A famous example is

# define square(x) ((x)*(x))
int i(2);
std::cout<<square(i++)<<", "<<i<<std::endl;

This will output
6, 4
and not the expected
4, 3
Another reason to avoid macros.
Hope that helps,

Sven.



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.