C++
Module 8: FunctionsBeginner45 min read

Recursion, Function Pointers & Callbacks

Understand direct/indirect recursion, call stack frames, tail recursion concepts, function pointers, and callback patterns.

Key Takeaways & Core Concepts
  • Direct vs. Indirect Recursion: Function A calls A vs. A calls B which calls A.
  • Tail Recursion: Recursive call is the very last operation; modern compilers with -O2 can optimize it into a loop (Tail Call Optimization).

1. Recursion & Call Stack Internals

Every recursive call pushes a stack frame (parameters, locals, return address). Always define a base case to terminate recursion and prevent Stack Overflow.

  • Direct vs. Indirect Recursion: Function A calls A vs. A calls B which calls A.
  • Tail Recursion: Recursive call is the very last operation; modern compilers with -O2 can optimize it into a loop (Tail Call Optimization).
1. Recursive Binary Search & Function Pointer
1#include <iostream>
2#include <vector>
3
4int binarySearch(const std::vector<int>& a, int l, int r, int target) {
5 if (l > r) return -1;
6 int mid = l + (r - l) / 2;
7 if (a[mid] == target) return mid;
8 return (a[mid] > target) ? binarySearch(a, l, mid - 1, target) : binarySearch(a, mid + 1, r, target);
9}
10
11int main() {
12 std::vector<int> v = {2, 5, 8, 12, 16, 23};
13 std::cout << "Index of 16: " << binarySearch(v, 0, (int)v.size() - 1, 16) << "\n";
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Divides search space in half each recursive call: O(log n) time.

2. Function Pointers & Callbacks

int (*op)(int, int) = add; stores the address of a function, enabling runtime strategy selection and C-style callbacks (whereas Modern C++ also offers lambdas and std::function).

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)