Core Module
12 min forge
C++ Function Basics
Defining and calling functions to modularize your code.
C++ Function Basics
π What is it
Functions are reusable blocks of code that perform a specific task. They help in reducing redundancy and making the code more readable and maintainable.
β‘ When to use
Always! Break down complex problems into smaller, manageable functions.
π§ Time complexity
- Call overhead: $O(1)$
- Execution: Depends on function body.
π» Code example
cpp Standard#include <iostream> // Declaration int add(int a, int b); int main() { int sum = add(5, 10); // Call std::cout << "Sum: " << sum << std::endl; return 0; } // Definition int add(int a, int b) { return a + b; }
β Common mistakes
- Not providing a function prototype if the definition is after
main(). - Returning the wrong type from a function.
- Defining a function inside another function (not allowed in standard C++).