Introduction
The call stack helps the computer remember where it is in a program when functions call other functions. It keeps track of what to do next after each function finishes.
/* In C, the call stack is managed automatically by the system. Each function call creates a stack frame that stores: - Function parameters - Local variables - Return address Example functions calling each other: */ #include <stdio.h> void functionB() { int localB = 20; printf("Inside functionB: localB = %d\n", localB); } void functionA() { int localA = 10; printf("Inside functionA: localA = %d\n", localA); functionB(); } int main() { functionA(); return 0; }
#include <stdio.h> void functionC() { printf("Inside functionC\n"); } void functionB() { printf("Inside functionB\n"); functionC(); } void functionA() { printf("Inside functionA\n"); functionB(); } int main() { functionA(); return 0; }
#include <stdio.h> void recursiveFunction(int count) { if (count == 0) { printf("Reached base case\n"); return; } printf("Count: %d\n", count); recursiveFunction(count - 1); } int main() { recursiveFunction(3); return 0; }
#include <stdio.h> void printStackLevel(int level) { printf("Function call level: %d\n", level); if (level > 0) { printStackLevel(level - 1); } } int main() { printf("Starting program\n"); printStackLevel(3); printf("Program finished\n"); return 0; }
void myFunction().function, def, or func are not valid in C.void func(int n) {
if (n == 0) return;
printf("%d ", n);
func(n - 1);
}
int main() {
func(3);
return 0;
}void foo() {
int x = 5;
bar();
}
void bar() {
printf("%d", x);
}
int main() {
foo();
return 0;
}int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int result = factorial(4);
printf("%d", result);
return 0;
}Pass the test and this pattern moves unknown