Functions
Overview
If you write all your code inside the main() function, your application will quickly become an unreadable, monolithic nightmare of 10,000 lines.
Functions (also called Methods or Subroutines) solve this by allowing you to break your program down into small, reusable, isolated blocks of logic. You write the logic once, give it a name, and can 'call' it infinitely throughout your codebase. This enforces the DRY principle (Don't Repeat Yourself), makes debugging drastically easier, and allows multiple engineers to work on different functions simultaneously without stepping on each other's toes.
Syntax
// 1. Function Declaration (Prototype)
// Tells the compiler the function exists before it's used
void sayHello();
int main() {
// 3. Function Call (Executing the logic)
sayHello();
return 0;
}
// 2. Function Definition (The actual logic)
void sayHello() {
std::cout << "Hello, World!\n";
}Common Pitfalls
- Calling a function before declaring it. In C++, the compiler reads files strictly top-to-bottom. If
main()tries to callcalculateMath()butcalculateMath()is defined belowmain(), the compiler will throw a fatal error. You must use 'Forward Declarations' (Function Prototypes) at the top of the file to fix this.
Interview Questions
.h header files) from Function Definitions (in .cpp source files)?This separation drastically speeds up compilation time in massive enterprise projects. If a function's underlying logic (the .cpp file) changes, the compiler only has to recompile that specific file. Any other file that simply #includes the header file does not need to be recompiled because the 'Declaration' (the signature) didn't change.
Real-World Example
Using Forward Declarations to allow functions to call each other regardless of their physical order in the file.
#include <iostream>
// Forward Declarations (Prototypes)
void ping();
void pong();
int main() {
ping(); // Starts the chain
return 0;
}
void ping() {
std::cout << "Ping!\n";
// Can call pong() because it was prototyped!
pong();
}
void pong() {
std::cout << "Pong!\n";
}Check Your Knowledge
Test your understanding of Functions with these quick questions.