C++ programming
Jakob Oestergaard
jakob at unthought.net
Mon Oct 21 11:57:30 PDT 2002
On Mon, Oct 21, 2002 at 11:00:08AM -0700, Greg Lindahl wrote:
> On Mon, Oct 21, 2002 at 07:51:57PM +0200, Jakob Oestergaard wrote:
>
> > The C example must *always* generate one function call to the
> > compare_int function whenever two elements of the array are compared.
>
> Nope. A good C compiler can generate multiple copies of a routine when it
> is sometimes called with constant arguments. In this case, the constant
> argument would be the compare_int function, and in the routine with that
> constant argument, compare_int could be inlined.
>
> Yes, there are C compilers that can do this. gcc isn't one of them.
Ok, if you're lucky enough to have your qsort routine available (in
source form) somewhere outside of /lib/libc.so. I didn't know that
compilers existed that can do what you say - but I can accept that one
exists when you say so :)
One more thing you get from using template functions is type safety. Now
before we start arguing whether real programmers might introduce bugs in
their code which could have been avoided with the help of a type-system,
there is again a speed benefit to stricter typing:
In the C example, I cast a void* to an int* - one half of the code works
on void* and another half on int*. In the C++ example, I always work on
int elements (or pointers to int elements).
Some compilers (GCC at least) have type-based aliasing analysis. By
actually using the correct types, instead of casted void* pointers
throughout your code, you not only help yourself (if you're the kind of
programmer that occationally might happen to pass the wrong thing to a
void* in C ;), you also help the compiler.
And mind you, this is not because the C compiler is stupid. It is
because there are optimizations which are simply not valid, unless
certain assumptions can be made based on the types of the data that is
being worked on.
There's some old information about the type aliasing in GCC at
http://gcc.gnu.org/news/alias.html
--
................................................................
: jakob at unthought.net : And I see the elder races, :
:.........................: putrid forms of man :
: Jakob Østergaard : See him rise and claim the earth, :
: OZ9ABN : his downfall is at hand. :
:.........................:............{Konkhra}...............:
More information about the Beowulf
mailing list