A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.
Syntax:

Syntax of Function
Example:
C++
// C++ Program to demonstrate working of a function
#include <iostream>
using namespace std;
// Following function that takes two parameters 'x' and 'y'
// as input and returns max of two input numbers
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// main function that doesn't receive any parameter and
// returns integer
int main()
{
int a = 10, b = 20;
// Calling above function to find max of 'a' and 'b'
int m = max(a, b);
cout << "m is " << m;
return 0;
}
Time complexity: O(1)
Space complexity: O(1)
Why Do We Need Functions?
- Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to make changes in only one place if we make changes to the functionality in future.
- Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read and use the code, if the code is divided into functions.
- Functions provide abstraction. For example, we can use library functions without worrying about their internal work.
Function Declaration
A function declaration tells the compiler about the number of parameters, data types of parameters, and returns type of function. Writing parameter names in the function declaration is optional but it is necessary to put them in the definition. Below is an example of function declarations. (parameter names are not present in the below declarations) The C++ Course provides comprehensive lessons on defining and using functions, enhancing your programming skills.

Function Declaration
Example:
C++
// C++ Program to show function that takes
// two integers as parameters and returns
// an integer
int max(int, int);
// A function that takes an int
// pointer and an int variable
// as parameters and returns
// a pointer of type int
int* swap(int*, int);
// A function that takes
// a char as parameter and
// returns a reference variable
char* call(char b);
// A function that takes a
// char and an int as parameters
// and returns an integer
int fun(char, int);
Types of Functions

Types of Function in C++
User Defined Function
User-defined functions are user/customer-defined blocks of code specially customized to reduce the complexity of big programs. They are also commonly known as “tailor-made functions” which are built only to satisfy the condition in which the user is facing issues meanwhile reducing the complexity of the whole program.
Library Function
Library functions are also called “built-in Functions“. These functions are part of a compiler package that is already defined and consists of a special function with special and different meanings. Built-in Function gives us an edge as we can directly use them without defining them whereas in the user-defined function we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.
Parameter Passing to Functions
The parameters passed to the function are called actual parameters. For example, in the program below, 5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the above program x and y are formal parameters.

Formal Parameter and Actual Parameter
There are two most popular ways to pass parameters:
- Pass by Value: In this parameter passing method, values of actual parameters are copied to the function’s formal parameters. The actual and formal parameters are stored in different memory locations so any changes made in the functions are not reflected in the actual parameters of the caller.
- Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes made inside the function are reflected in the actual parameters of the caller.
Function Definition
Pass by value is used where the value of x is not modified using the function fun().
C++
// C++ Program to demonstrate function definition
#include <iostream>
using namespace std;
void fun(int x)
{
// definition of
// function
x = 30;
}
int main()
{
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Time complexity: O(1)
Space complexity: O(1)
Functions Using Pointers
The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address.
C++
// C++ Program to demonstrate working of
// function using pointers
#include <iostream>
using namespace std;
void fun(int* ptr) { *ptr = 30; }
int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}
Time complexity: O(1)
Space complexity: O(1)
passing string as an argument:
In c++ we can pass string as as argument in various way
- Pass by Value
- Pass by Reference
- Pass by Pointer
1. Pass by Value
In this when you are passing a values as string it will make a copy of a string values.
C++
#include <iostream>
#include <string>
void printString(std::string str) {
std::cout << str << std::endl;
}
int main() {
std::string myString = "Hello, GFG!";
printString(myString);
return 0;
}
2. Pass by Reference
This can be done by using ‘&’ operator
C++
#include <iostream>
#include <string>
void printString(const std::string& str) { // Note the 'const' to prevent modification
std::cout << str << std::endl;
}
int main() {
std::string myString = "welcome to gfg";
printString(myString);
return 0;
}
3. Pass by Pointer
This can be done by using * operator
C++
#include <iostream>
#include <string>
void printString(const std::string* str) { // Note the 'const' to prevent modification
std::cout << *str << std::endl;
}
int main() {
std::string myString = "This is Pss by pointer";
printString(&myString);
return 0;
}
OutputThis is Pss by pointer
Returning string from a function:
This can be done by using the function “std::string”
C++
#include <iostream>
#include <string>
std::string getGreeting() {
return "This is C++";
}
int main() {
std::string greeting = getGreeting();
std::cout << greeting << std::endl;
return 0;
}
Returning a pointer from a function
we need to create a function that returns a pointer to an array of integers.
C++
#include <iostream>
int* createArray(int size) {
int* arr = new int[size]; // Dynamically allocate memory for an array
for (int i = 0; i < size; ++i) {
arr[i] = i * 10; // Initialize array elements
}
return arr; // Return the pointer to the array
}
int main() {
int size = 10;
int* myArray = createArray(size); // Function returns a pointer to the array
// Print the array
for (int i = 0; i < size; ++i) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
delete[] myArray; // Don't forget to free the allocated memory
return 0;
}
Output0 10 20 30 40 50 60 70 80 90
Callback function (function passed as an argument in other function)
A callback function is a function that is passed as an argument to another function
C++
#include <iostream>
// Define a callback function type
typedef void (*CallbackFunction)();
// Function that takes a callback function as an argument
void performAction(CallbackFunction callback) {
std::cout << "Performing some action...\n";
// Call the callback function
callback();
}
// Example callback function
void myCallback() {
std::cout << "Callback function \n";
}
int main() {
// Pass the callback function to performAction
performAction(myCallback);
return 0;
}
OutputPerforming some action...
Callback function
An array of function pointer and how the elements are accessed
Here, we have c++ example, for accessing elements from array
C++
#include <iostream>
// Function declarations
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
// Declare and initialize an array of function pointers
int (*funcArray[3])(int, int) = { add, subtract, multiply };
// Variables to use as function parameters
int x = 2, y = 3;
// Access and call the functions using the array of function pointers
std::cout << "Add: " << funcArray[0](x, y) << std::endl; // Calls add(10, 5)
std::cout << "Subtract: " << funcArray[1](x, y) << std::endl; // Calls subtract(10, 5)
std::cout << "Multiply: " << funcArray[2](x, y) << std::endl; // Calls multiply(10, 5)
return 0;
}
OutputAdd: 5
Subtract: -1
Multiply: 6
Difference between call by value and call by reference in C++
| Call by value | Call by reference |
|---|
| A copy of the value is passed to the function | An address of value is passed to the function |
Changes made inside the function are not reflected on other functions | Changes made inside the function are reflected outside the function as well |
Actual and formal arguments will be created at different memory location | Actual and formal arguments will be created at same memory location. |
Points to Remember About Functions in C++
1. Most C++ program has a function called main() that is called by the operating system when a user runs the program.
2. Every function has a return type. If a function doesn’t return any value, then void is used as a return type. Moreover, if the return type of the function is void, we still can use the return statement in the body of the function definition by not specifying any constant, variable, etc. with it, by only mentioning the ‘return;’ statement which would symbolize the termination of the function as shown below:
C++
void function name(int a)
{
....... // Function Body
return; // Function execution would get terminated
}
3. To declare a function that can only be called without any parameter, we should use “void fun(void)“. As a side note, in C++, an empty list means a function can only be called without any parameter. In C++, both void fun() and void fun(void) are same.
Main Function
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.
Types of Main Functions
1. Without parameters:
CPP
// Without Parameters
int main() { ... return 0; }
2. With parameters:
CPP
// With Parameters
int main(int argc, char* const argv[]) { ... return 0; }
The reason for having the parameter option for the main function is to allow input from the command line. When you use the main function with parameters, it saves every group of characters (separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return statement in the code. The number that is returned is used to inform the calling program what the result of the program’s execution was. Returning 0 signals that there were no problems.
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn’t perform any task after function call, is known as tail recursion. In tail recursion, we generally call the same function with return statement.
Syntax:
We have Direct recursion and in direct recursion
1. Direct Recursion:
it can be done when the function calls itself
C++
#include <iostream>
using namespace std;
void directRecursion(int n) {
if (n > 0) {
cout << n << " ";
directRecursion(n - 1); // Function calls itself
}
}
int main() {
directRecursion(10);
return 0;
}
2. Indirect Recursion
In this One function calls another function .
C++
#include <iostream>
using namespace std;
void indirectRecursionB(int n); // Forward declaration
void indirectRecursionA(int n) {
if (n > 0) {
cout << n << " ";
indirectRecursionB(n - 1); // Function A calls Function B
}
}
void indirectRecursionB(int n) {
if (n > 1) {
cout << n << " ";
indirectRecursionA(n / 2); // Function B calls Function A
}
}
int main() {
indirectRecursionA(10);
return 0;
}
Tail Recursion and Non-Tail Recursion:
1. Tail Recursion:
Tail recursion occurs when a function makes a recursive call as its last operation,
C++
#include <iostream>
using namespace std;
void tailRecursion(int n) {
if (n > 0) {
cout << n << " ";
tailRecursion(n - 1); // Recursive call is the last operation
}
}
int main() {
tailRecursion(15);
return 0;
}
Output15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
2. Non-Tail Recursion
Non-tail recursion occurs when a function performs some operations after the recursive call.
C++
#include <iostream>
using namespace std;
int nonTailRecursion(int n) {
if (n > 0) {
return n + nonTailRecursion(n - 1); // Recursive call is not the last operation
} else {
return 0;
}
}
int main() {
int result = nonTailRecursion(20);
cout << "Result: " << result << endl;
return 0;
}
C++ Passing Array to Function
In C++, to reuse the array logic, we can create a function. To pass an array to a function in C++, we need to provide only the array name.
function_name(array_name[]); //passing array to function
Example: Print the minimum number in the given array.
C++
#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int ar[5] = { 30, 10, 20, 40, 50 };
printMin(ar); // passing array to function
}
void printMin(int arr[5])
{
int min = arr[0];
for (int i = 0; i < 5; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
cout << "Minimum element is: " << min << "\n";
}
// Code submitted by Susobhan Akhuli
OutputMinimum element is: 10
Time complexity: O(n) where n is the size of the array
Space complexity: O(n) where n is the size of the array.
C++ Overloading (Function)
If we create two or more members having the same name but different in number or type of parameters, it is known as C++ overloading. In C++, we can overload:
- methods,
- constructors and
- indexed properties
Types of overloading in C++ are:
- Function overloading
- Operator overloading
C++ Function Overloading
Function Overloading is defined as the process of having two or more functions with the same name, but different parameters. In function overloading, the function is redefined by using either different types or number of arguments. It is only through these differences a compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because you don’t need to use different names for the same action.
Example: changing number of arguments of add() method
C++
// program of function overloading when number of arguments
// vary
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a, int b) { return a + b; }
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void)
{
Cal C; // class object declaration.
cout << C.add(10, 20) << endl;
cout << C.add(12, 20, 23);
return 0;
}
// Code Submitted By Susobhan Akhuli
Time complexity: O(1)
Space complexity: O(1)
Example: when the type of the arguments vary.
C++
// Program of function overloading with different types of
// arguments.
#include <iostream>
using namespace std;
int mul(int, int);
float mul(float, int);
int mul(int a, int b) { return a * b; }
float mul(double x, int y) { return x * y; }
int main()
{
int r1 = mul(6, 7);
float r2 = mul(0.2, 3);
cout << "r1 is : " << r1 << endl;
cout << "r2 is : " << r2 << endl;
return 0;
}
// Code Submitted By Susobhan Akhuli
Outputr1 is : 42
r2 is : 0.6
Time Complexity: O(1)
Space Complexity: O(1)
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded function, this situation is known as function overloading ambiguity.
When the compiler shows the ambiguity error, the compiler does not run the program.
Causes of Ambiguity:
- Type Conversion.
- Function with default arguments.
- Function with pass-by-reference.
Type Conversion:-
C++
#include <iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i) { cout << "Value of i is : " << i << endl; }
void fun(float j)
{
cout << "Value of j is : " << j << endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
// Code Submitted By Susobhan Akhuli
The above example shows an error “call of overloaded ‘fun(double)’ is ambiguous“. The fun(10) will call the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. If we replace float to double, the program works. Therefore, this is a type conversion from float to double.
Function with Default Arguments:-
C++
#include <iostream>
using namespace std;
void fun(int);
void fun(int, int);
void fun(int i) { cout << "Value of i is : " << i << endl; }
void fun(int a, int b = 9)
{
cout << "Value of a is : " << a << endl;
cout << "Value of b is : " << b << endl;
}
int main()
{
fun(12);
return 0;
}
// Code Submitted By Susobhan Akhuli
The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous“. The fun(int a, int b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).
Function with Pass By Reference:-
C++
#include <iostream>
using namespace std;
void fun(int);
void fun(int&);
int main()
{
int a = 10;
fun(a); // error, which fun()?
return 0;
}
void fun(int x) { cout << "Value of x is : " << x << endl; }
void fun(int& b)
{
cout << "Value of b is : " << b << endl;
}
// Code Submitted By Susobhan Akhuli
The above example shows an error “call of overloaded ‘fun(int&)’ is ambiguous“. The first function takes one integer argument and the second function takes a reference parameter as an argument. In this case, the compiler does not know which function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &).
Friend Function
- A friend function is a special function in C++ which in spite of not being a member function of a class has the privilege to access private and protected data of a class.
- A friend function is a non-member function or an ordinary function of a class, which is declared by using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
- The keyword “friend” is placed only in the function declaration but not in the function definition.
- When the friend function is called neither the name of the object nor the dot operator is used. However, it may accept the object as an argument whose value it wants to access.
- A friend function can be declared in any section of the class i.e. public, private, or protected.
Declaration of friend function in C++
Syntax:
class <class_name> {
friend <return_type> <function_name>(argument/s);
};
Example_1: Find the largest of two numbers using Friend Function
C++
#include <iostream>
using namespace std;
class Largest {
int a, b, m;
public:
void set_data();
friend void find_max(Largest);
};
void Largest::set_data()
{
cout << "Enter the first number : ";
cin >> a;
cout << "\nEnter the second number : ";
cin >> b;
}
void find_max(Largest t)
{
if (t.a > t.b)
t.m = t.a;
else
t.m = t.b;
cout << "\nLargest number is " << t.m;
}
int main()
{
Largest l;
l.set_data();
find_max(l);
return 0;
}
Output
Enter the first number : 789
Enter the second number : 982
Largest number is 982
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc. This C++ tutorial is designed to provide a guide for s
6 min read
C++ Overview
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. C++ is a high-level, general-purpose programming language designed for system and application programming. It was dev
7 min read
Features of C++
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including: Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopu
6 min read
History of C++
The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++
C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development Environment
C++ 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
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
C++ Basics
Writing First C++ Program - Hello World Example
The "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 is used to demonstrate how the coding process works. All you have to do is display the message "Hello World" on the
3 min read
C++ Basic Syntax
Syntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language. The C++ language also has its syntax for the functionalities it provides. Different statements have differen
4 min read
C++ Comments
Comments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work. E
3 min read
Tokens in C
In C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ Keywords
Keywords are the reserved words that have special meanings in the C++ language. They are the words that the language uses for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name or function name or any other identifiers. Let's take a lo
2 min read
Difference between Keyword and Identifier in C
In C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language. The below table illustrates the primary dif
3 min read
C++ Variables and Constants
C++ Variables
In 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 variabl
5 min read
Constants in C
In C programming, constants are read-only values that cannot be modified during the execution of a program. These constants can be of various types, such as integer, floating-point, string, or character constants. They are initialized with the declaration and remain same till the end of the program.
3 min read
Scope of Variables in C++
In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using names
7 min read
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
7 min read
Static Keyword in C++
The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses. In C++, a static keyword can be used in the following context: Table of Content Static Variables in a FunctionStatic Member Var
5 min read
C++ Data Types and Literals
C++ Data Types
Data 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 ty
6 min read
Literals in C
In C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++
The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality. In C++, there are four different derived data types: Table of Co
4 min read
User Defined Data Types in C++
User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types: Table of Content ClassStruc
4 min read
Data Type Ranges and Their Macros in C++
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
4 min read
C++ Type Modifiers
In C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store. C++ have 4 type modifiers which are as follows: Table of Content signed Modifierunsigned
4 min read
Type Conversion in C++
Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { // Two variables of
4 min read
Casting Operators in C++
The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer). Let's take a look at an example: [G
5 min read
C++ Operators
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in C
In C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
Assignment Operators in C
In C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error. Let's take a look at an example: [GFGTAB
5 min read
C++ sizeof Operator
The sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespac
3 min read
Scope Resolution Operator in C++
In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example: [GFGTABS] C++ #include <iostream> int main() { // Accessing cout from std namespace usin
3 min read
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
C++ if else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
4 min read
C++ if else if Ladder
In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++
In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
6 min read
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function. In C++, there is four jump statement: Table of Content continue Statementbreak Statementreturn Statementgot
4 min read
C++ Loops
In 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. [GFGTABS] C++ #include <iostream> using namesp
7 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Let's take a look at an example: [GFGTABS] C++ #include <bit
6 min read
Range-Based for Loop in C++
In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops. Let's take
3 min read
C++ While Loop
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.In s
15+ min read
return Statement in C++
In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the argum
5 min read
Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing. Call By Va
4 min read
Default Arguments in C++
A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value. Example: [GFGTABS] C++ /
6 min read
Inline Functions in C++
In C++, a function can be specified as inline to reduce the function call overhead. The whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of using normal function call mechanism. Example: [GFGTABS] C++ #include <iostream> using
5 min read
Lambda Expression in C++
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. Example: [GFGTABS] C++ //Driver Code Starts{ #include <
5 min read
C++ Pointers and References
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
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you're workin
9 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in C
Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++
Consider the following C++ program that shows problem with NULL (need of nullptr) [GFGTABS] CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Over
3 min read
References in C++
In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x;
6 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing
5 min read
When do we pass arguments by pointer?
In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read