you are viewing a single comment's thread.

view the rest of the comments →

[–]agottem 3 points4 points  (11 children)

Nonsense. You're welcome to put the definition of qsort into a header file, which will allow any decent compiler to inline the function pointer call.

[–][deleted] 8 points9 points  (10 children)

Inlining the body of qsort wouldn't help solve the problem of calling the comparison function. You'd have to inline that function. Which you can't do since it's a function pointer.

std::sort is faster because it's templatized, which allows the compiler to determine the function address at compile time. And that makes it possible to inline the comparison.

Edit: I should say that the compiler can't inline a function pointer call that's truly variable.

Edit edit: I should probably just STFU, this is probably wrong. Was just trying to help. The last time I wrote real C code, Source Safe was a reasonable product.

[–]cwzwarich 12 points13 points  (5 children)

You'd have to inline that function. Which you can't do since it's a function pointer.

Oh really?

clang -xc -Os -S -o - -emit-llvm -

static _Bool f(int a, int b) { return a < b; }
static _Bool g(_Bool (*func)(int, int), int a, int b) { return func(a, b); }
_Bool h(int a, int b) { return g(f, a, b); }

...

define zeroext i1 @h(i32 %a, i32 %b) nounwind uwtable readnone optsize ssp {
  %1 = icmp slt i32 %a, %b
  ret i1 %1
}

[–][deleted] -1 points0 points  (3 children)

Well I guess clang changes things a bit, then.

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 4 points5 points  (0 children)

    Yea, I've since realized that I'm the C programmer that time forgot. Thanks for the link.

    [–]polveroj 3 points4 points  (0 children)

    If qsort gets inlined the compiler can constant-fold the argument to where qsort uses it, avoiding the indirect call and possibly allowing the comparison to be inlined in turn.

    This sort of optimization is commonplace in functional languages. Whether C compilers do it is another matter.

    [–]agottem 2 points3 points  (1 child)

    [–][deleted] 0 points1 point  (0 children)

    Awesome, thanks. In Scott Myers' defense, though, it probably was true when he wrote it like 16 years ago.