A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the modularity and reusability.
Function Definition
A function definition specifies the function name, what type of value it returns and what it does. In C++, a function must be defined before it its used.
C++ return_type name() { // Function body }
- return_type: Type of value the function returns.
- name: Name assigned to the function.
- Function body: Set of statements in curly brackets { } are executed when the function is called.
Example:
C++ // Defining function that prints hello void printHello(){ cout << "Hello Geeks"; }
The above function is named printHello. Only the single statement that prints "Hello Geeks" is the part of function body. The return type of the function is void, which is used when function does not return anything.
Function Call
Once the function is defined, we can use it anywhere in the program simply by calling it using its name with () parenthesis.
Example:
C++ #include <bits/stdc++.h> using namespace std; void printHello(){ cout << "Hello Geeks"; } int main() { // Calling function fun printHello(); return 0; }
The function printHello is called using its name in the main along with parenthesis. When called, printHello's body is executed and the text "Hello Geeks" is printed.
Return Type
We have seen an example of function that does not return anything. But functions can return some value as a result of its execution. The type of this value should be defined as the return_type of the function.
Example:
C++ #include <bits/stdc++.h> using namespace std; // Defining function that returns 10 int getTen(){ int res = 10 return res; } int main() { // Calling function getTen() cout << getTen(); return 0; }
In this example, the getTen() function is supposed to return the integer value. So, the return type of the function is specified as int. Then the return keyword is used to return the variable res from the function to the point where it is called. The call of the function is replaced by the value it returns, so res, whose value is 10 is printed.
Note: Only one value can be returned from the function, and it must be of the same type as of function's return type.
Parameters or Arguments
A function can also take some input data to process. These values are called function arguments and are supplied to the function at the function call. To receive these values, we define placeholder variables called parameter inside parenthesis in function definition. They should be specified with their types and names.
C++ return_type name(type1 name1, type2 name2...) { // Function body return val; }
name1, name2 and so on are the parameter names using which they will be accessed in the function.
Example:
C++ #include <bits/stdc++.h> using namespace std; // Defining function that prints given number void printNum(int n){ cout << n << endl; } int main() { int num1 = 10; int num2 = 99; // Calling printNum and passing both // num1 and num2 to it one by one printNum(num1); printNum(num2); return 0; }
In the above program, printNum() function is defined with one integer parameter n that it prints. It means that it will take one value of integer type while calling and print it. We called printNum() two times, one with num1 and one with num2, and in each call, it prints the given number. Note that we refer to the passed argument using the name n not num1 or num2 in the function. It is due to the concept called scope of variables in the main and printNum() function.
Here, there can be one question. Why didn't we call the function with both numbers at once? The answer lies in the printNum() definition. We have defined the function that only takes one value of integer type as parameter, so we cannot pass two values. In other words,
A function can only take as many arguments as specified in the function definition and it is compulsory to pass them while calling it. Also, they should be of same type as in the function definition.
There are also other different ways to pass arguments to the function in C++. Refer to this article to know more - Parameter Passing Techniques in C++
Forward Declaration
In C++, a function must be defined before its call. Otherwise, compiler will throw an error. To resolve this, we can just declare the function before the call and definition to inform the compiler about function's name and return type. This is called forward declaration or just function declarations.
C++
Above is the function declaration that tells the compiler that there is a function with the given name and return type in the program. Writing parameter in the function declaration is optional but valid.
C++ return_type name(type1, type2 ...);
The above variation of the function declaration is also called function prototype or function signature. If this declaration is present before the function call, then we have the freedom to define the function anywhere in the program.
Note: Function declarations are compulsory, but the function definition already contains the function declaration as a part of it, so it is not explicitly needed when function is defined at the start.
Library Functions
Until now, we have discussed function which we define by ourselves. These functions are called user defined functions for obvious reasons.
C++ also provides some in-build functions that are already defined inside different libraries to simplify some commonly performed tasks. These functions are Library Functions which can be directly called to perform the task.
Example:
C++ #include <iostream> #include <algorithm> using namespace std; int main() { int n = 3; int m = 6; // Call library function max() that // returns maximum value between two // numbers cout << max(3, 6); return 0; }
The max() function in the above code returns the larger value among two values passed as argument. It is defined in the algorithm library, so we had to include the relevant header file <algorithm> to use it.
Similarly, C++ provides a lot of in-built functions to make our life easier. It is preferred to use in-built functions wherever we can.
Default Arguments
Earlier, we said that it is compulsory to pass all the arguments in the function call. But C++ also provides a work around for this. For each function argument, a default value can be defined that will be used when no value is passed for that argument in the function call. These are called default arguments in C++. If a function has more than one parameter, default values are assigned from right to left. This means that default values can only be provided for the rightmost parameters.
Example:
C++ #include <iostream> using namespace std; // Function with default arguments int getSum(int x, int y = 20) { return x+y; } int main() { cout << getSum(5) << endl; cout << getSum(5, 15); return 0; }
In this code, the getSum() function takes two parameters, with y having a default value of 20. When called with one argument, the default value for y is used. When two arguments are provided, both x and y are used to calculate the sum.
Main Function
As you may have noticed from the above program, main is also the function. In C++, the main function is a special function that every C++ program must contain. It serves as the entry point for the program. The computer will start running the code from the beginning of the main function. The return value of the main function indicates the successful or unsuccessful execution of the program.
Recursion
When function is called within the same function, it is known as recursion. The function which calls itself is known as recursive function and such calls are called recursive calls. Recursion is an important concept in programming that simplifies a lot of problems are complex to handle using normal programming means.
Function Overloading
Up until now, we know that an identifier can only be used only once in the program. The name of the function is also an identifier, so it should be unique as well.
Image a scenario where you have a function that performs the multiplication of two integers, but you also need to a function that multiplies two integers that are in the form of strings. Normally, you may have to use two functions with different names for this purpose. In large codebase, there can be many such cases and creating and remembering the names of these functions can be hectic.
This problem can be solved though function overloading. Function overloading refers to the feature in C++ where two or more functions can have the same name but different parameters. It allows us to use the same function name for different arguments but same purpose. This helps in clean semantically understandable code.
Lamda Functions in C++
Functions in C++ are declared and defined in global scope or class scope. So, C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem