TECHNOLOGY 

Published on

Calculating a Factorial in C – Notes

1. Purpose of the C Factorial Example

  • Demonstrates the same logic previously used in ARM assembly.
  • Helps visualize how high-level C code becomes low-level machine code.

2. Why C Instead of Python?

  • C is a compiled language; Python is interpreted.
  • Compiled C code can be disassembled to view its machine-level instructions.

3. Example C Code


int factorial(int n)
{
  int result = n;

  while(--n > 0)
  {
    result = result * n;
  }

  return result;
}
    

4. How the Function Works

  • Receives n as input.
  • Initializes result with n.
  • Decrements n before multiplying.
  • Returns the computed factorial.

5. Walkthrough Example (n = 4)

Step n result Explanation
Init 4 4 Function starts
1 3 12 4 × 3
2 2 24 12 × 2
3 1 24 24 × 1
End - 24 Final return
✅ Final Output: factorial(4) = 24

6. Note on --n in the While Loop

  • --n decreases n before the condition check.
  • Ensures the loop multiplies from n-1 down to 1.

7. Advantages of the C Version

  • More readable than assembly code.
  • Not processor-specific — portable across systems.

8. Compiled ARM Assembly Output


0001051c  sub   r3, r0, #1
00010520  cmp   r3, #0
00010524  bxle  lr
00010528  mul   r0, r3, r0
0001052c  subs  r3, r3, #1
00010530  bne   00010528
00010534  bx    lr
    

9. Disassembly Insight

  • C source code → machine code → disassembled to readable assembly.
  • Even without the source, compiled programs can be analyzed.

10. Cross-Platform Compilation Example (x86)

The same C code compiled for a 32-bit x86 processor:


00406c35  mov   ecx, dword ptr [esp+4]
00406c39  mov   eax, ecx
00406c3b  jmp   00406c40
00406c3d  imul  eax, ecx
00406c40  dec   ecx
00406c41  test  ecx, ecx
00406c43  jg    00406c3d
00406c45  ret
    
Conclusion: High-level languages like C provide readability and portability, while compilers handle processor-specific translation.
0 Comments