C++ Function (With Examples) (2024)

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem:

  • a function to draw the circle
  • a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and reusable.

There are two types of function:

  1. Standard Library Functions: Predefined in C++
  2. User-defined Function: Created by users

In this tutorial, we will focus mostly on user-defined functions.

C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes defined in the body of the function.

C++ Function Declaration

The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) { // function body }

Here's an example of a function declaration.

// function declarationvoid greet() { cout << "Hello World";}

Here,

  • the name of the function is greet()
  • the return type of the function is void
  • the empty parentheses mean it doesn't have any parameters
  • the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function

In the above program, we have declared a function named greet(). To use the greet() function, we need to call it.

Here's how we can call the above greet() function.

int main() { // calling a function greet(); }
C++ Function (With Examples) (1)

Example 1: Display a Text

#include <iostream>using namespace std;// declaring a functionvoid greet() { cout << "Hello there!";}int main() { // calling the function greet(); return 0;}

Output

Hello there!

Function Parameters

As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.

For example, let us consider the function below:

void printNum(int num) { cout << num;}

Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.

int main() { int n = 7; // calling the function // n is passed to the function as argument printNum(n); return 0;}

Example 2: Function with Parameters

// program to print a text#include <iostream>using namespace std;// display a numbervoid displayNum(int n1, float n2) { cout << "The int number is " << n1; cout << "The double number is " << n2;}int main() { int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); return 0;}

Output

The int number is 5The double number is 5.5

In the above program, we have used a function that has one int parameter and one double parameter.

We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively.

C++ Function (With Examples) (2)

Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration.

Return Statement

In the above programs, we have used void in the function declaration. For example,

void displayNumber() { // code}

This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.

For example,

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

Here, we have the data type int instead of void. This means that the function returns an int value.

The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code after return inside the function is not executed.

Example 3: Add Two Numbers

// program to add two numbers using a function#include <iostream>using namespace std;// declaring a functionint add(int a, int b) { return (a + b);}int main() { int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0;}

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.

We pass two int literals 100 and 78 while calling the function.

We store the returned value of the function in the variable sum, and then we print it.

C++ Function (With Examples) (3)

Notice that sum is a variable of int type. This is because the return value of add() is of int type.

Function Prototype

In C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,

// function prototypevoid add(int, int);int main() { // calling the function before declaration. add(5, 3); return 0;}// function definitionvoid add(int a, int b) { cout << (a + b);}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters. That's why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype

// using function definition after main() function// function prototype is declared before main()#include <iostream>using namespace std;// function prototypeint add(int, int);int main() { int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0;}// function definitionint add(int a, int b) { return (a + b);}

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.

That's why we have used a function prototype in this example.

Benefits of Using User-Defined Functions

  • Functions make the code reusable. We can declare them once and use them multiple times.
  • Functions make the program easier as each small task is divided into a function.
  • Functions increase readability.

C++ Library Functions

Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath.

Example 5: C++ Program to Find the Square Root of a Number

#include <iostream>#include <cmath>using namespace std;int main() { double number, squareRoot; number = 25.0; // sqrt() is a library function to calculate the square root squareRoot = sqrt(number); cout << "Square root of " << number << " = " << squareRoot; return 0;}

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.

The function declaration of sqrt() is defined in the cmath header file. That's why we need to use the code #include <cmath> to use the sqrt() function.

Also Read:

  • C++ Standard Library functions.
  • C++ User-defined Function Types
C++ Function (With Examples) (2024)

FAQs

What are some examples of function in C++? ›

List of C++ Functions
  • Print: std::cout. This is the standard output stream object used for printing to the console. ...
  • Maximum: std::max. The maximum function returns the larger of two numbers. ...
  • Minimum: std::max. ...
  • Uppercase: std::toupper. ...
  • Input: std::cin. ...
  • New Line: std::end1. ...
  • Vector: std::vector. ...
  • Sort: std::sort.
Jun 27, 2023

What does good() do in C++? ›

ios good() function in C++ with Examples

It means that this function will check if this stream has raised any error or not. Syntax: bool good() const; Parameters: This method does not accept any parameter.

What is an inbuilt function in C++? ›

Built-in functions are ones for which the compiler generates inline code at compile time. Every call to a built-in function eliminates a runtime call to the function having the same name in the dynamic library.

What are the predefined functions in C++? ›

List of top 10 inbuilt functions in C++
  • pow()
  • sqrt()
  • min()
  • max()
  • swap()
  • gcd()
  • toupper()
  • tolower()
Apr 18, 2023

What are the 4 types of functions in C++? ›

There are four types of user-defined functions divided on the basis of arguments they accept and the value they return:
  • Function with no arguments and no return value.
  • Function with no arguments and a return value.
  • Function with arguments and no return value.
  • Function with arguments and with return value.
Jun 22, 2023

What is the best example of a function? ›

An example of a simple function is f(x) = x2. In this function, the function f(x) takes the value of “x” and then squares it. For instance, if x = 3, then f(3) = 9. A few more examples of functions are: f(x) = sin x, f(x) = x2 + 3, f(x) = 1/x, f(x) = 2x + 3, etc.

What are the four built in functions in C++? ›

Useful Inbuilt Functions in C++
  • sqrt() Function. The sqrt() function is used to determine the square root of the value of type double. ...
  • pow() Function. The pow() function is used to find the value of the given number raised to some power. ...
  • sort() Function. ...
  • find() Function. ...
  • binary_search() Function. ...
  • 6 . ...
  • 7 . ...
  • swap() Function.
Oct 16, 2023

What is the main function in C++? ›

The main function is a special function. Every C++ program must contain a function named main. It serves as the entry point for the program. The computer will start running the code from the beginning of the main function.

What is the friend function in C++? ›

A friend function is a function that isn't a member of a class but has access to the class's private and protected members. Friend functions aren't considered class members; they're normal external functions that are given special access privileges.

What are the 4 parts of a function in C++? ›

The main part of functions is return_type, function_name, parameter and functions body.

How to declare functions in C++? ›

C++ Function Declarations & Definitions

The syntax for a function declaration is: return_type function_name(parameter_list); In this example, int is the return type of the function, add is the name of the function, and (int x, int y) is the parameter list that specifies two integer parameters called “x” and “y.”

What is void in C++ with an example? ›

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

What are the examples of functions in C? ›

The examples of these types of functions in C are printf(), scanf(), puts(), gets(), floor(), ceil(), etc. User-defined functions: The functions which the programmer creates are called user-defined functions. The user-defined functions in C should be declared and defined before being used.

What are the main functions of C++? ›

main() Function in C++

main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

What is considered a function in C++? ›

A function is a block of code that performs some operation. A function can optionally define input parameters that enable callers to pass arguments into the function. A function can optionally return a value as output.

What is an example of a power function in C++? ›

For example: Given two numbers base and the exponent, pow() function evaluates x with respect to the power of y i.e. x^y. Example – pow(4 , 2); Then we will get the result as 4^2, which is 16. the power 4.0, which equals 81. the power 3.0, which equals 343.

References

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6174

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.