Creating programs by breaking them into smaller chunks is a popular practice among programmers. These sections are called modules or procedures and typically carry out individual tasks. In C++, these modules are usually referred to as functions.
In this tutorial, we will discuss in detail the fundamentals of functions, such as their types, components, parameters, arguments, and more.
C++ Functions
A function in C++ is a block of code that performs a specific task. Functions are used to break up large programs into smaller and more manageable parts. They also allow for code reuse and modular programming, making debugging and maintaining programs easier.
In simple terms, when a set of related statements, structured in a specific way and used to achieve a particular task, are combined together, it is known as a function.
Understanding The Concept of Functions in C++
Using functions in C++ can save time by allowing a programmer to write a set of code once and call upon them multiple times within the same program. This eliminates the need to repeat the same instructions over and over again.
For example, suppose a programmer wanted to print out a series of messages to the console as part of a program. In that case, they could create a function that prints out the messages and then call the function multiple times throughout the program instead of writing out the same instructions for each message. This would save the programmer time and make the code easier to read and maintain.
Types of Functions in C++
C++ functions can be divided into two types: functions that are already created and available for use (built-in functions) and functions that are created by the user (user-defined functions).
User-defined Functions
User-defined functions are functions that are created by the user to perform specific tasks. They are written in C++ and are used to extend the functionality of the language. User-defined functions can be used to perform calculations, display output, or perform other tasks.
The advantage of user-defined functions is that they allow the programmer to write code that is tailored to the specific needs of the program.
Syntax of Functions in C++
The following is the general syntax of functions in C++:
return_type function_name(parameter_list)
{
// function body
body_of_function
}
For example,
int addTwoNumbers(int num1, int num2)
{
int result = num1 + num2;
return result;
}
Here,
1. int
: the data type of the value the function will return. In this case, the function will return an integer.
2. addTwoNumbers
: the name of the function.
3. { }
: the body of the function’s code block.
4. (int num1, int num2)
: the parameters of the function. This function takes two integers as inputs.
5. int result = num1 + num2;
: this line assigns the sum of the two parameters to a local variable called result.
6. return result;
: this line returns the value stored in the result variable.
Example 1: A C++ Program To Show The Working of a Function
#include <iostream> using namespace std; // Function definition int addTwoNumbers(int num1, int num2) { int result = num1 + num2; return result; } int main() { // Variables to store the two numbers int num1, num2; cout << "Enter The First Number: "; cin >> num1; cout << "Enter The Second Number: "; cin >> num2; // Function call int result = addTwoNumbers(num1, num2); cout << "The Result is: " << result << endl; return 0; }
OUTPUT OF THE PROGRAM
Enter The First Number: 5
Enter The Second Number: 3
The Result is: 8
The above program is a simple example of using a function in a C++ program. The program takes two numbers as input from the user, adds them together, and then displays the result.
The function is named addTwoNumbers
, and it takes two parameters, num1
and num2
, which are both integers.
The main()
function first declares two variables, num1
and num2
, which will be used to store the two numbers that will be added together. The user is then prompted to enter the two numbers, which are then stored in the variables.
The addTwoNumbers()
function is then called, passing in the two numbers as parameters. The function adds the two numbers together and stores the result in a local variable called the result
. This result is then returned from the function and stored in the result
variable in main()
.
Finally, the result is printed to the console with a message.
Example 2: A C++ Program To Demonstrate The Concept Of C++ Functions
#include <iostream> using namespace std; // Function definition int addTwoNumbers() { int num1, num2; cout << "Enter The First Number: "; cin >> num1; cout << "Enter The Second Number: "; cin >> num2; int result = num1 + num2; return result; } int main() { // Function call int result = addTwoNumbers(); cout << "The Result is: " << result << endl; return 0; }
OUTPUT OF THE PROGRAM
Enter The First Number: 10
Enter The Second Number: 5
The Result is: 15
Here,
Example 2 is similar to Example 1 but without parameters. In Example 1, two numbers are passed as parameters to the addTwoNumbers()
function, which adds them and returns the result. In Example 2, the addTwoNumbers()
function does not have any parameters and instead takes input from the user within the function itself. The function then adds the two numbers and returns the result.
Components of Functions in C++
A user-defined function consists of the following components:
Function Declaration
The following is the general syntax of a function declaration:
function functionName(parameter1, parameter2, ...) {
// code to be executed
}
For example,
//function declaration
void displayMessage() {
cout << "Hello World!" ;
}
Here,
1. void
is the return type of the function. It indicates that the function does not return any value.
2. displayMessage
is the name of the function.
3. ()
is used to declare the function’s parameters. Since there are no parameters in this function, the parentheses are empty.
4. The {
indicates the start of the function’s code body.
5. cout << "Hello World!";
is the actual code that is executed when the function is called.
6. Finally, the }
marks the end of the code body.
Calling a Function
In the function declaration, we’ve declared a function called displayMessage()
. Now, in order to use it in the program, we’ve to call it.
Here’s how you can call the displayMessage()
function in the program:
int main() {
// calling the function
displayMessage();
}
Example 3: Declaring and Calling a Function in C++
#include <iostream> using namespace std; //function declaration void displayMessage() { cout << "Hello World!" ; } int main() { // calling the function displayMessage(); return 0; }
OUTPUT OF THE PROGRAM
Hello World!
Function Parameters
Function parameters are values that are passed to a function when it is called. When a function is called, the number and type of the parameters should match the number and type of the parameters in the function definition. When a function is called, the arguments passed to it are assigned to its respective parameters in the same order.
For example, consider the following C++ program. This program defines a function named add
that takes two integer parameters, a
and b
, and returns the sum of the two parameters.
#include <iostream> using namespace std; void add(int a, int b) { int result = a + b; cout << result << endl; } int main() { int x = 2; int y = 3; add(x, y); return 0; }
OUTPUT OF THE PROGRAM
5
Here,
The function add
takes two integer parameters, a
and b
.
These parameters are passed to the function when it is called in the main()
function.
The value of the two parameters, in this case, 2
and 3
, are passed to the add()
function and stored as the variables a
and b
.
The add()
function then adds the two variables together, stores the result in a new variable called result
, and prints out the result to the console.
Return Statement
The function declaration in the aforementioned programs uses the void return type. For example:
void add() {
// function body
body_of_function
}
The void
return type is used when a function does not return any value. It is used to indicate that the function does not return a value. In the above example, the function add()
does not return any value, so it is declared with the void
return type.
To return a value from a function, the function must be declared with a return type that matches the type of the value that is being returned. For example, if an integer value is to be returned from a function, the function must be declared with an int
return type.
For example, if the function add()
were to return the sum of two values, it would be declared as follows:
int add (int x, int y) {
return (x + y);
}
Here,
The program takes two int
parameters, x
and y
, and returns the sum of those two parameters. The function uses the int
type instead of the void
because it is expected to return an integer value. The function will add the two int
parameters together and return the result. When a function ends, it is indicated by a return
statement. Within the function, no code is run after the return
statement.
For example,
#include <iostream> using namespace std; // declaring a function int add(int x, int y) { return (x + y); } int main() { int sum; // storing the value returned // from the function call in the sum variable. sum = add(4, 6); cout << "4 + 6 = " << sum << endl; return 0; }
OUTPUT OF THE PROGRAM
4 + 6 = 10
Function Prototype
In C++, a function must be declared before it is called. However, if the function needs to be declared after the call, a function prototype must be used, so the compiler knows the signature of the function.
Function prototypes in C++ are declarations that allow the compiler to verify that a function is being called correctly. They are placed at the beginning of a program, usually before main()
, and they tell the compiler the return type, name, and parameters of the function. A function prototype is written as follows:
return_type function_name(parameter_list);
For example, if you have a function called add()
that takes two integers as parameters and returns an integer, the prototype would look like this:
int add(int, int);
That’s all there is to it! Function prototypes are important for ensuring that functions are called correctly and that the compiler can check types.
Example 4: Function Prototype Program Example in C++
#include <iostream> using namespace std; // declaring the function prototype int add(int x, int y); int main() { int sum; // calling the function sum = add(8, 7); cout << "8 + 7 = " << sum << endl; return 0; } // defining the function int add(int x, int y) { return (x + y); }
OUTPUT OF THE PROGRAM
8 + 7 = 15
Here,
The program declares a function prototype for the function add
which takes two integer parameters and returns an integer value. The function prototype declares the function without providing its definition.
The main function calls the add
function and stores the value returned from the function call in the sum
variable. The add
function is defined after the main()
function. The add function returns the sum of two integers passed to it as parameters.
Advantages Of Using User-defined Functions
1. Code Reuse: User-defined functions allow you to reuse code, which can be especially useful when performing complex calculations or executing multiple tasks. This also makes your code easier to maintain and debug.
2. Modularization: Functions allow you to break down a large program into smaller and more manageable parts. This makes it easier to read and test the code.
3. Readability: Functions make your code easier to read and understand. By breaking down your code into smaller, more logical pieces, you can make it easier to identify and debug errors.
4. Efficiency: Functions can help improve the efficiency of your code by reducing the amount of duplicate code. This can help reduce the overall size of your program as well.
5. Efficiency: User-defined functions can also help to improve the performance of your code by allowing you to optimize certain functions for specific tasks. This can help speed up the overall execution time of your program.
Library or Built-in Functions
Built-in functions are functions that are included in the C++ language itself, as opposed to being user-defined functions. They are generally used to perform a specific task, such as input/output, mathematical computation, and memory allocation.
The following are the commonly used built-in functions in C++:
1. Input/Output Functions: These functions are used to read and write data to and from the console or files. Examples include cout
, cin
, getline()
, getch()
, etc.
2. Mathematical Functions: These functions are used to perform mathematical operations such as addition, subtraction, multiplication, division, and more. Examples include sqrt()
, pow()
, abs()
, sin()
, cos()
, tan()
, etc.
3. Memory Allocation Functions: These functions are used to allocate and deallocate memory from the heap. Examples include malloc()
, free()
, calloc()
, realloc()
, etc.
4. String Manipulation Functions: These functions are used to manipulate string data. Examples include strlen()
, strcpy()
, strcat()
, strcmp()
, etc.
5. Time and Date Functions: These functions are used to get the current time and date. Examples include time()
, localtime()
, mktime()
, strftime()
, etc.
6. Type Casting Functions: These functions are used to convert one data type to another. Examples include int()
, float()
, char()
, etc.
7. Miscellaneous Functions: These functions are used for other purposes. Examples include exit()
, abort()
, assert()
, etc.
Example 5: A C++ Program That Will Demonstrates The Use Of Built-in Functions in C++
#include <iostream> #include <cmath> //include the cmath library to use the built-in math functions using namespace std; int main() { int x = 8; //declare an int variable cout << "The value of x is: " << x << endl; //print the value of x //abs() is a built-in function that returns the absolute value of a number cout << "The absolute value of x is: " << abs(x) << endl; //print the absolute value of x //sqrt() is a built-in function that returns the square root of a number cout << "The square root of x is: " << sqrt(x) << endl; //print the square root of x //pow() is a built-in function that returns the value of a number to the power of another number cout << "x to the power of 2 is: " << pow(x, 2) << endl; //print x to the power of 2 return 0; }
OUTPUT OF THE PROGRAM
The value of x is: 10
The absolute value of x is: 10
The square root of x is: 3.16228
x to the power of 2 is: 100
Here,
The cmath
a library function is included to access math functions like abs()
, sqrt()
, and pow()
. The program declares an int variable x
, then prints its value, absolute value, square root, and x
to the power of 2
using the respective built-in functions.
2 comments
This tutorial is an excellent resource for learning the fundamentals of C++ functions. The explanations are clear and concise, and the examples are very helpful. Thank you for putting in the effort to create such a great tutorial! ?
Thank you for your feedback!