Functions in C++

📘 C++ 👁 38 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

A function is a block of code that performs a specific task. Functions help in code reusability, modularity, and readability.


Advantages of Functions

  • Reduces code duplication

  • Improves readability

  • Makes debugging easier

  • Supports modular programming


Types of Functions in C++

  1. Library (Built-in) Functions
    Example: cout, cin, sqrt()

  2. User-Defined Functions
    Created by the programmer


Structure of a Function

return_type function_name(parameter_list) { // function body return value; }

Example of a User-Defined Function

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

Function Declaration (Prototype)

Tells the compiler about the function before its use.

int add(int, int);

Function Definition

Contains the actual code.

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

Function Call

Executes the function.

int result = add(5, 3);

Complete Program Example

#include using namespace std; int add(int, int); int main() { int sum = add(10, 20); cout << sum>return 0; } int add(int a, int b) { return a + b; }

Types of Function Arguments

  1. Call by Value
    Values are copied

  2. Call by Reference
    Address is passed

Example:

void swap(int &a, int &b) { int temp = a; a = b; b = temp; }

Inline Functions

Expands function code at the point of call.

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

Recursive Functions

A function that calls itself.

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

Key Points

  • Functions improve program structure

  • Function prototype is important

  • Supports recursion and reuse

  • Call by reference allows value modification


Conclusion

Functions are fundamental in C++ programming and play a key role in writing efficient and organized programs.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes