C++ Functions


Functions in C++ are an essential part of writing organized, reusable, and efficient code. They allow you to divide your program into smaller, logical sections. Each function performs a specific task, which makes your code easier to read, maintain, and debug.

What is a Function in C++?

A function is a block of code that performs a specific operation and can be executed whenever needed. Instead of writing the same code multiple times, you can define a function once and call it whenever required.

Syntax of a Function

returnType functionName(parameters) {
    // function body
}

Example:

#include <iostream>
using namespace std;

void greet() {
    cout << "Hello, welcome to C++ programming!";
}

int main() {
    greet(); // function call
    return 0;
}

Output:

Hello, welcome to C++ programming!

Here:

  • void is the return type (no value returned).

  • greet() is the function name.

  • The function is called inside main().

Types of Functions in C++

C++ supports two main types of functions:

  1. Built-in Functions – Functions already defined in libraries, such as sqrt(), strlen(), or pow().

  2. User-defined Functions – Functions you create based on your program’s needs.

Function Declaration and Definition

Before calling a function, it must be declared so the compiler knows about its existence.

Function Declaration

A function declaration (also known as a prototype) tells the compiler about the function’s name, return type, and parameters.

Syntax:

returnType functionName(parameterType1, parameterType2);

Example:

int add(int, int);

Function Definition

A function definition includes the body (actual code) of the function.

Example:

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

Function Call

A function call executes the defined function.

int result = add(10, 20);
cout << "Sum: " << result;

Function with Parameters and Return Value

Functions can accept input values (parameters) and return output values.

Example:

#include <iostream>
using namespace std;

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

int main() {
    int result = multiply(4, 5);
    cout << "Product: " << result;
}

Output:

Product: 20

Void Functions

A void function doesn’t return any value. It performs a task, like displaying output.

Example:

void displayMessage(string name) {
    cout << "Hello " << name << ", welcome to C++!";
}

Function Return Types

A function can return any data type — int, float, char, string, or even objects.

Example:

string getLanguage() {
    return "C++";
}

int main() {
    cout << "Language: " << getLanguage();
}

Output:

Language: C++

Passing Arguments to Functions

There are two ways to pass arguments to a function in C++:

1. Pass by Value

A copy of the variable is passed to the function. Changes made inside the function don’t affect the original variable.

Example:

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

int main() {
    int num = 50;
    changeValue(num);
    cout << num; // remains 50
}

2. Pass by Reference

The actual variable is passed, so changes inside the function reflect in the original variable.

Example:

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

int main() {
    int num = 50;
    changeValue(num);
    cout << num; // changes to 100
}

Default Arguments in Functions

You can assign default values to parameters. If a value isn’t passed, the default one is used.

Example:

void introduce(string name, string language = "C++") {
    cout << "Hello, I'm " << name << " and I love " << language << endl;
}

int main() {
    introduce("Aarushi");
    introduce("Neha", "Python");
}

Output:

Hello, I'm Aarushi and I love C++
Hello, I'm Neha and I love Python

Function Overloading Overview

C++ allows you to create multiple functions with the same name but different parameter lists. This is called function overloading.
You’ll learn it in detail in the upcoming tutorial.

Inline Functions

An inline function is expanded in place when called, reducing function call overhead for small functions.

Example:

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

When you call square(5), the compiler replaces it directly with 5 * 5.

Recursive Functions

A recursive function calls itself until a condition is met.
It’s useful for problems like factorial, Fibonacci, or traversing data structures.

Example:

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

You’ll explore recursion in detail later.

Advantages of Using Functions in C++

  • Reusability: Define once, use multiple times.

  • Modularity: Divide large programs into manageable parts.

  • Ease of Maintenance: Easy to debug and modify.

  • Code Clarity: Improves readability and organization.

Summary of C++ Functions

  • Functions help break code into smaller, reusable parts.

  • They can have parameters and return values.

  • Functions can be passed by value or by reference.

  • Default arguments and overloading add flexibility.

  • Inline and recursive functions improve performance and logic clarity.


Practice Questions

  1. Write a function to find the maximum of two numbers.

  2. Create a function to check whether a number is even or odd.

  3. Write a function that returns the GCD of two integers.

  4. Write a function to calculate the factorial of a number.

  5. Create a function that counts vowels in a given string.

  6. Write a function to swap two numbers using call by reference.

  7. Define a function that calculates the area of a circle.

  8. Write a function with a default argument for greeting a user.

  9. Create a function to check if a number is prime.

  10. Write a function that reverses a given integer number.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top