Ugenz Academy/Tutorial

Function

13 min read2,460 words

Reading progress

Keep learning

C++ Functions

1. Introduction

A function in C++ is a block of code designed to perform a specific task. Functions help divide a large program into smaller, manageable, and reusable parts.

Instead of writing the same code repeatedly, we can write it once inside a function and call it whenever needed.

Example

#include <iostream> using namespace std; void greet() { cout << "Hello, Welcome to C++!"; } int main() { greet(); return 0; }

Output

Hello, Welcome to C++!

Here, greet() is a function that displays a message.

2. Why Use Functions?

Functions are useful because they:

  • Reduce code repetition
  • Make programs easier to understand
  • Make programs easier to debug
  • Improve code organization
  • Allow code reuse
  • Make large programs easier to manage
  • Separate different tasks into different blocks

3. Basic Syntax of a Function

return_type function_name(parameters) { // statements }

Example

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

Parts of a Function

PartDescription
intReturn type
addFunction name
int a, int bParameters
return a + b;Value returned by the function

4. Function Declaration

A function declaration tells the compiler about a function before it is used.

Syntax

return_type function_name(parameters);

Example

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

Output

30

The statement:

int add(int, int);

is called a function declaration or function prototype.

5. Function Definition

A function definition contains the actual code that performs the task.

Example

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

Here, the function performs addition and returns the result.

6. Function Call

A function call is used to execute a function.

Example

greet();

Complete example:

#include <iostream> using namespace std; void greet() { cout << "Hello!"; } int main() { greet(); return 0; }

Output

Hello!

7. Types of Functions

C++ functions can generally be classified into:

  1. Library functions
  2. User-defined functions

7.1 Library Functions

Library functions are predefined functions provided by C++ libraries.

Examples:

sqrt() pow() strlen()

Example

#include <iostream> #include <cmath> using namespace std; int main() { cout << sqrt(25); return 0; }

Output

5

7.2 User-Defined Functions

Functions created by the programmer are called user-defined functions.

Example

#include <iostream> using namespace std; void display() { cout << "This is a user-defined function."; } int main() { display(); return 0; }

8. Function with No Parameter and No Return Value

A function may not receive any input and may not return any value.

Example

#include <iostream> using namespace std; void display() { cout << "Welcome to C++"; } int main() { display(); return 0; }

Output

Welcome to C++

Here:

  • No parameter is passed.
  • The return type is void.

9. Function with Parameters but No Return Value

A function can receive values but does not return a value.

Example

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

Output

Sum = 30

10. Function with No Parameters but Return Value

A function can return a value without receiving parameters.

Example

#include <iostream> using namespace std; int getNumber() { return 100; } int main() { int number = getNumber(); cout << number; return 0; }

Output

100

11. Function with Parameters and Return Value

A function can receive parameters and return a value.

Example

#include <iostream> using namespace std; int multiply(int a, int b) { return a * b; } int main() { int result = multiply(5, 4); cout << "Result = " << result; return 0; }

Output

Result = 20

This is one of the most commonly used forms of functions.

12. Parameters and Arguments

These two terms are related but different.

Parameter

A variable defined in the function declaration or definition is called a parameter.

int add(int a, int b)

Here, a and b are parameters.

Argument

The actual values passed when calling a function are called arguments.

add(10, 20);

Here, 10 and 20 are arguments.

Difference

ParameterArgument
Appears in function definitionAppears in function call
Acts as a variableRepresents actual value
Example: a, bExample: 10, 20

13. Return Statement

The return statement sends a value back to the calling function.

Example

int square(int n) { return n * n; }

Calling the function:

cout << square(5);

Output

25

A function with a non-void return type normally needs to return a compatible value.

14. Void Function

A function with no return value uses the void return type.

Example

void message() { cout << "Hello"; }

The function does not return a value.

15. Passing Arguments by Value

In pass by value, a copy of the argument is passed to the function.

Changes made inside the function do not affect the original variable.

Example

#include <iostream> using namespace std; void change(int x) { x = 100; } int main() { int a = 10; change(a); cout << a; return 0; }

Output

10

The original value remains unchanged.

16. Passing Arguments by Reference

In pass by reference, the function receives a reference to the original variable.

Changes made inside the function affect the original variable.

Example

#include <iostream> using namespace std; void change(int &x) { x = 100; } int main() { int a = 10; change(a); cout << a; return 0; }

Output

100

Here, int &x is a reference parameter.

17. Passing Arguments Using Pointers

A pointer can also be used to modify the original variable.

Example

#include <iostream> using namespace std; void change(int *x) { *x = 100; } int main() { int a = 10; change(&a); cout << a; return 0; }

Output

100

18. Default Arguments

A default argument is a value automatically used when the caller does not provide an argument.

Example

#include <iostream> using namespace std; void display(int age = 18) { cout << "Age = " << age; } int main() { display(); return 0; }

Output

Age = 18

If we write:

display(25);

the output will be:

Age = 25

19. Multiple Parameters

A function can have multiple parameters.

Example

#include <iostream> using namespace std; int calculate(int a, int b, int c) { return a + b + c; } int main() { cout << calculate(10, 20, 30); return 0; }

Output

60

20. Function Overloading

Function overloading means creating multiple functions with the same name but different parameter lists.

Example

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int main() { cout << add(10, 20) << endl; cout << add(10.5, 20.5); return 0; }

Output

30 31

The compiler determines which function to call based on the arguments.

Important

Functions cannot be overloaded only by changing their return type.

Incorrect:

int test(); double test();

This is not valid function overloading.

21. Inline Functions

An inline function is a function declared using the inline keyword.

Example

#include <iostream> using namespace std; inline int square(int x) { return x * x; } int main() { cout << square(5); return 0; }

Output

25

The inline keyword suggests that the compiler may expand the function at the point where it is called. Modern compilers may make their own optimization decisions.

22. Recursive Function

A recursive function is a function that calls itself.

Example: Factorial

#include <iostream> using namespace std; int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { cout << factorial(5); return 0; }

Output

120

How It Works

factorial(5) = 5 × factorial(4) = 5 × 4 × factorial(3) = 5 × 4 × 3 × factorial(2) = 5 × 4 × 3 × 2 × factorial(1) = 120

A recursive function needs a base condition to stop recursion.

23. Lambda Functions

C++ also supports lambda expressions, which are small anonymous functions.

Example

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

Output

30

Lambda functions are useful when a small function is needed temporarily.

24. Scope of Variables in Functions

Variables declared inside a function are generally local to that function.

Example

#include <iostream> using namespace std; void test() { int x = 10; cout << x; } int main() { test(); return 0; }

Here, x is a local variable and can only be directly accessed within its scope.

25. Global Variables and Functions

A global variable is declared outside all functions.

Example

#include <iostream> using namespace std; int number = 50; void display() { cout << number; } int main() { display(); return 0; }

Output

50

Global variables can be accessed by functions subject to normal C++ scope and linkage rules.

26. Function Returning Multiple Values

A normal C++ function can return one object/value, but multiple results can be grouped into a structure, pair, tuple, or another object.

Example Using pair

#include <iostream> using namespace std; pair<int, int> calculate(int a, int b) { return {a + b, a - b}; } int main() { auto result = calculate(20, 10); cout << "Sum = " << result.first << endl; cout << "Difference = " << result.second; return 0; }

Output

Sum = 30 Difference = 10

27. Function Calling Another Function

One function can call another function.

Example

#include <iostream> using namespace std; void second() { cout << "Second function"; } void first() { cout << "First function" << endl; second(); } int main() { first(); return 0; }

Output

First function Second function

28. main() Function

The main() function is the entry point of a normal C++ program.

Example

int main() { // program statements return 0; }

Program execution starts from main().

29. Complete Function Example

The following program takes two numbers from the user and calculates their sum.

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { int x, y; cout << "Enter two numbers: "; cin >> x >> y; int result = add(x, y); cout << "Sum = " << result; return 0; }

Example Output

Enter two numbers: 10 20 Sum = 30

30. Advantages of Functions

  • Code Reusability: The same function can be called multiple times.
  • Modularity: Large programs can be divided into smaller parts.
  • Easy Debugging: Errors can be isolated within individual functions.
  • Easy Maintenance: Changes can be made in one place.
  • Improved Readability: Functions make programs easier to understand.
  • Reduced Code Duplication: Repeated code can be placed inside a function.
  • Team Development: Different functions can be developed and tested separately.

31. Disadvantages of Functions

  • Too many small functions can make a program difficult to follow.
  • Function calls can introduce some overhead, although optimization can reduce it.
  • Incorrect parameter or return-type design can make functions harder to use.
  • Poorly designed functions can create unnecessary dependencies.

32. Important Rules for Functions

  1. A function should have a meaningful name.
  2. Parameters should have meaningful names.
  3. The return type should match the returned value.
  4. A void function does not need to return a value.
  5. A non-void function should normally return an appropriate value.
  6. Function names are case-sensitive.
  7. Function parameters are separated using commas.
  8. A function can call another function.
  9. A function can be called multiple times.
  10. Recursive functions need a stopping/base condition.
  11. Functions cannot be overloaded only by return type.
  12. Function declarations are useful when the definition appears later in the source file.

33. Function vs Function Call

FunctionFunction Call
Defines a taskExecutes the task
Contains function bodyUses function name with arguments
Example: int add(int a, int b)Example: add(10, 20)
Created by programmerUsed when the function needs to run

34. Summary Table

ConceptMeaning
FunctionBlock of code that performs a specific task
DeclarationAnnounces a function to the compiler
DefinitionContains the implementation of a function
Function CallExecutes a function
ParameterVariable received by a function
ArgumentActual value passed to a function
ReturnSends a value back to the caller
voidIndicates no return value
Default ArgumentAutomatically used when an argument is omitted
OverloadingSame function name with different parameter lists
RecursionFunction calling itself
LambdaSmall anonymous function

35. Conclusion

Functions are one of the most important concepts in C++. They allow programmers to divide a program into smaller and reusable parts. Functions improve code organization, readability, reusability, debugging, and maintenance.

Understanding function declaration, definition, parameters, arguments, return values, references, overloading, and recursion provides a strong foundation for learning advanced C++ concepts such as classes, objects, inheritance, polymorphism, and templates.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy