Lesson 8 of 45
C++Lesson 8: Functions
6 min
Course progress18%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 8 of 45
C++6 min
Keep these ideas in mind as you work through the lesson.
Functions encapsulate reusable logic, promote modular design, and enable recursion. A C++ function has a return type, a name, a parameter list, and an optional function body. You can forward‑declare a function before defining it, which helps resolve circular dependencies.
// Forward declaration
double factorial(int n);
int main() {
std::cout << \"5! = \" << factorial(5) << '\
';
return 0;
}
// Definition
double factorial(int n) {
if (n <= 1) return 1.0; // base case
return n * factorial(n - 1); // recursive case
}
Key points:
inline functions hint the compiler to expand the body at call sites (use inline or define inside a class).constexpr functions can be evaluated at compile time if arguments are constant.Tip: Keep functions short – ideally one responsibility – to improve readability and testability.
<Alert type="info">The compiler may ignore the inline suggestion; modern optimisers decide automatically.