C++ Functions with Program Examples (2024)

What is a Function in C++?

A function in C++ refers to a group of statements that takes input, processes it, and returns an output. The idea behind a function is to combine common tasks that are done repeatedly. If you have different inputs, you will not write the same code again. You will simply call the function with a different set of data called parameters.

Each C++ program has at least one function, the main() function. You can divide your code into different functions. This division should be such that every function does a specific task.

There are many built-in functions in the C++ standard library. You can call these functions within your program.

Why use functions?

There are numerous benefits associated with the use of functions. These include:

  • Each function puts related code together. This makes it easier for programmers to understand code.
  • Functions make programming easier by eliminating code repetition.
  • Functions facilitate code reuse. You can call the same function to perform a task at different sections of the program or even outside the program.

Built-in Functions

In C++ library functions are built-in C++ functions. To use these functions, you simply invoke/call them directly. You do not have to write the functions yourself.

Example 1:

#include <iostream>#include <cmath>using namespace std;int main() {double num, squareRoot;cout << "Enter number: ";cin >> num;squareRoot = sqrt(num);cout << "The square root of " << num << " is: " << squareRoot;return 0;}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the cmath library to use its functions. We want to use the function sqrt() defined in it.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should be added within the body of this function.
  5. Declare two double variables, num, and squareRoot.
  6. Print some text on the console. The text asks the user to enter a number.
  7. Read user input from the keyboard. The input will become the value of variable num.
  8. Call the library function sqrt(), which calculates the square root of a number. We passed the parameter num to the function, meaning it will calculate the square root of num. This function is defined in the cmath library.
  9. Print the number entered by the user, its square root, and some other text on the console.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

User-Defined Functions

C++ allows programmers to define their own functions. The purpose of the function is to group related code. The code is then given a unique identifier, the function name.

The function can be called/invoked from any other part of the program. It will then execute the code defined within its body.

Example 2:

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

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Create a user-defined function named sayHello().
  4. Print some text on the console when the sayHello() function is called.
  5. End of the body of the sayHello() function.
  6. Call the main() function. The program logic should be added within the body of this function.
  7. Call/invoke the function named sayHello().
  8. The program must return value upon successful completion.
  9. End of the body of the main() function.

Function Declaration/Prototype

If you define a user-defined function after the main() function, the C++ compiler will return an error. The reason is that the compiler does not know the details of the user-defined function. The details include its name, the types of arguments, and their return types.

In C++, the function declaration/prototype declares a function without a body. This gives the compiler details of the user-defined function.

In the declaration/prototype, we include the return type, the function name, and argument types. The names of arguments are not added. However, adding the argument names generates no error.

Function Definition

The purpose of the function declaration is to tell the C++ compiler about the function name, the return type, and parameters. A function definition tells the C++ compiler about the function body.

Syntax

return_datatype function_name( parameters) { function body }

From the above, a function definition has the function header and body. Here is an explanation of the parameters:

  • return_datatype- Some functions return value. This parameter denotes the data type of the return value. Some functions don’t return value. In that case, the value of this parameter becomes void.
  • function_name- This is the name of the function. The function name and parameters form the function signature.
  • Parameters- This is the type, the order, and the number of function parameters. Some functions don’t have parameters.
  • function body- these are statements defining what the function will do.

Function Call

For a function to perform the specified task and return output, it must be called. When you call a function, it executes the statements added within its body.

A program is called by its name. If the function takes parameters, their values should be passed during the call. If the service takes no parameters, don’t pass any value during the call.

Passing Arguments

In C++, an argument/parameter is the data passed to a function during its call. The values must be initialized to their respective variables.

When calling a function, the arguments must match in number. The means the values you pass must be equal to the number of parameters. Again, the values must also match the parameters in terms of type. If the first parameter is an integer, the value passed to it must be an integer.

One can assign default values to function parameters. If you don’t pass a value for the parameter during the function call, the default value will be used.

Example 3: How to Write and Call a Function

#include <iostream>using namespace std;int addFunc(int, int);int main() {int x, y, sum;cout << "Enter two numbers: ";cin >> x >> y;sum = addFunc(x, y);cout <<"The sum of "<<x<< " and " <<y<<" is: "<<sum;return 0;}int addFunc(int num1, int num2) {int addFunc;addFunc = num1 + num2;return addFunc;}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Declare a function named addFunc() that takes two integer parameters. This creates the function prototype.
  4. Call the main() function. The program logic should be added within the body of this function.
  5. Declare three integer variables, x, y, and sum.
  6. Print some text on the console. The text asks the user to enter two numbers.
  7. Read the user input from the keyboard. The user should enter two numbers for variables x and y, separated by space.
  8. Call the function addFunc() and passing to it the parameters x and y. The function will operate on these parameters and assign the output to the variable sum.
  9. Print the values of variables x, y, and sum on the console alongside other text.
  10. The function must return value upon successful completion.
  11. End of the body of the main() function.
  12. Function definition. We are defining the function addFunc(). We will state what the function will do within its body, the { }.
  13. Declaring an integer variable named addFunc.
  14. Adding the values of parameters num1 and num2 and assigning the result to variable addFunc.
  15. The addFunc() function should return the value of addFunc variable.
  16. End of the function body, that is, function definition.

Summary

  • A function in C++ helps you group related code into one.
  • Functions facilitate code reuse.
  • Instead of writing similar code, again and again, you simply group it into a function. You can then call the function from anywhere within the code.
  • Functions can be library or user-defined.
  • Library functions are the functions built-in various C++ functions.
  • To use library functions, you simply include its library of definition and call the function. You don’t define the function.
  • User-defined functions are the functions you define as a C++ programmer.
  • A function declaration tells the compiler about the function name, return type, and parameter types.
  • A function definition adds the body of the function.
  • If a function takes parameters, their values should be passed during the function call.

You Might Like:

  • C++ Polymorphism with Example
  • How to Download and Install C++ IDE on Windows
  • Hello World Program in C++ with Code Explanation
  • C++ Tutorial for Beginners: Learn Programming Basics in 7 Days
  • Difference between Structure and Class in C++
  • C++ Tutorial PDF for Beginners (Download Now)
  • Static Member Function in C++ (Examples)
C++ Functions with Program 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 is important in a function in C++? ›

The required parts of a function declaration are: The return type, which specifies the type of the value that the function returns, or void if no value is returned. In C++11, auto is a valid return type that instructs the compiler to infer the type from the return statement. In C++14, decltype(auto) is also allowed.

Can you do functional programming in C++? ›

C++ 11 brings a number of new tools for functional-style programming. Perhaps most important, C++ now has support for lambdas (also known as closures or anonymous functions). Lambdas allow you to compose your code in ways that wouldn't have been practical before.

What is a user defined function in C++? ›

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.

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

Functions with arguments and return values. Functions with arguments and without return values. Functions without arguments and with return values. Functions without arguments and without return values.

What is an example of a function in a program? ›

We use the function name followed by the argument list in parentheses to call a function. For example, we can use the following code to call the sum function that we defined earlier: int a = 5; int b = 10; int c = sum(a, b); In this code, we are calling the sum function with a and b as its parameters.

What function must every C++ program have? ›

Every C++ program must include one free function named main. This is the function that executes when you run the program.

What is the most important thing in C++? ›

Object-Oriented Programming

C++ is an Object-Oriented Programming Language, unlike C which is a procedural programming language. This is the most important feature of C++. It can create/destroy objects while programming. Also, It can create blueprints with which objects can be created.

How many main functions should a C++ program have? ›

The main() function

Every program must have one function named main , and the following constraints apply: No other function in the program can be called main . main cannot be defined as inline or static . main cannot be called from within a program.

Can we write C++ program without main function? ›

All C++ programs must have a main function. If you try to compile a C++ program without a main function, the compiler raises an error. (Dynamic-link libraries and static libraries don't have a main function.)

Which is better, Python or C++? ›

C++ duel lacks a clear winner, as the better choice depends on individual preferences and project requirements. Python excels in quick learning and the rapid development of small programs. In contrast, C++ is suitable for large projects and exploring multiple languages, although it requires more time to master.

Can I do everything with C++? ›

All kinds of programmers use C++ to write code and build programs, whether it's part of a work project or just as a hobby. Because the language is so versatile, you can use it for tasks that range from the very simple to the incredibly complex.

What is a function in C++ with an example? ›

A function definition requires a name, a group of parameters, a return type, and a body. It may either return a variable, value, or nothing (specified by the keyword void). For example, the simple function defined below returns an integer which is the double of the value you pass into it.

What are recursive functions in C++? ›

A function in C++ is an important concept that includes the function definition, function declaration, function body, etc. In this article, we will learn about C++ recursion: a recursive function is a particular function that calls itself repeatedly until a certain condition is met.

How to use pointer in C++? ›

Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double ) too.

What are function examples? ›

A few more examples of functions are: f(x) = sin x, f(x) = x2 + 3, f(x) = 1/x, f(x) = 2x + 3, etc. There are several types of functions in maths. Some important types are: Injective function or One to one function: When there is mapping for a range for each domain between two sets.

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 are functions in C with examples? ›

A function in C is a set of statements that when called perform some specific task. It is the basic building block of a C program that provides modularity and code reusability. The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain operations.

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: Rev. Porsche Oberbrunner

Last Updated:

Views: 6172

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.