C++ Functions

πŸ”§ C++ Functions

A function in C++ is a block of code that performs a specific task.
Functions help make programs modular, reusable, readable, and easier to maintain.


πŸ”Ή 1. Why Use Functions?

  • Avoid code repetition

  • Improve readability

  • Easier debugging and maintenance

  • Divide a program into logical parts


πŸ”Ή 2. Function Syntax

return_type function_name(parameters) {
// function body
return value; // optional (void functions)
}

πŸ”Ή 3. Simple Function Example

void greet() {
cout << "Hello, World!";
}

Calling the function:

greet();

πŸ”Ή 4. Function with Parameters

void add(int a, int b) {
cout << a + b;
}

Call:

add(10, 20);

πŸ”Ή 5. Function with Return Value

int sum(int a, int b) {
return a + b;
}

Call:

int result = sum(5, 7);

πŸ”Ή 6. Function Declaration (Prototype)

Used when function is defined after main().

int multiply(int, int); // declaration

int main() {
cout << multiply(3, 4);
}

int multiply(int a, int b) {
return a * b;
}


πŸ”Ή 7. Call by Value

void change(int x) {
x = 100;
}

Original value not changed.


πŸ”Ή 8. Call by Reference

void change(int &x) {
x = 100;
}

Original value is changed.


πŸ”Ή 9. Function with Pointer Parameters

void change(int *x) {
*x = 50;
}

πŸ”Ή 10. Default Arguments

int add(int a, int b = 10) {
return a + b;
}

Call:

add(5); // 15
add(5, 20); // 25

πŸ”Ή 11. Inline Functions

inline int square(int x) {
return x * x;
}

βœ” Reduces function call overhead
❌ Large functions not suitable


πŸ”Ή 12. Function Overloading

int add(int a, int b);
double add(double a, double b);

Same name, different parameters.


πŸ”Ή 13. Recursion (Function Calling Itself)

int factorial(int n) {
if (n == 1)
return 1;
return n * factorial(n - 1);
}

πŸ”Ή 14. main() Function

int main() {
// program starts here
return 0;
}

❌ Common Mistakes

void func() {
return 10; // ❌ void cannot return value
}

πŸ“Œ Summary

  • Functions are reusable code blocks

  • Can take parameters and return values

  • Support overloading, recursion, default arguments

  • Improve program structure and clarity

You may also like...