Topic 28 of 83
Functions
Overview
Functions break large tasks into smaller, modular, reusable pieces. A function must be declared (prototype) before it is used, and defined (implementation) somewhere in the code.
Syntax
cpp
// Declaration (Prototype)
int add(int a, int b);
int main() {
int sum = add(5, 3); // Calling
return 0;
}
// Definition
int add(int a, int b) {
return a + b;
}Common Pitfalls
- Forgetting to declare the function before `main()`, resulting in a 'was not declared in this scope' compiler error.
Interview Tips
- Explain that prototypes allow functions to call each other regardless of the order they are defined in the file. Header files (.h) are essentially lists of function prototypes.
Real-World Example
Separating declaration from definition.
example
cpp
#include <iostream>
using namespace std;
// Prototype
void printBanner();
int main() {
printBanner(); // Call
return 0;
}
// Implementation
void printBanner() {
cout << "======================\n";
cout << " SYSTEM ACTIVATED \n";
cout << "======================\n";
}