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++).