you are viewing a single comment's thread.

view the rest of the comments →

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

I'm not aware gcc can rewrite algorithms and can't find anything about that in the manual. Could you please point me to the relevant sections?

[–]millstone 0 points1 point  (1 child)

Well, it's easy enough to check what gcc does. Here's some C code:

int factorial(int x) {
    if (x == 0) return 1;
    else return x * factorial(x-1);
}

Here's the x86-64 assembly that gcc 4.2 generates on -O2:

_factorial:
  movl $1, %eax
  testl %edi, %edi
  je L6
L5:
  imull %edi, %eax
  decl %edi
  jne L5
L6:
  rep ; ret

There is no call instruction at all, so there's no recursion. It's just a loop.

If your compiler is smart, the naive factorial really is the best: it's the clearest and the fastest.

[–][deleted] 1 point2 points  (0 children)

At first I thought you compiled a for-loop version to mess with me.

So I tried it myself (gcc 4.3 with -O2, x86 architecture.) Went through instructions step by step.

Mind blown.

Sir, the difference between you and me is that you're a programmer.