×

Call by Pointer in C++

What is Pointer?

Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined as a variable that stores the memory address of another variable.

 It enables the programmer to manage the memory.

The C++ language has a wide range of pointer-based features.

It has characteristics like the ability to refer to the same memory location from several memory locations, which means that we can update one point in the program and have the changes appear in other areas.

It is feasible to have a more flexible memory allocation and deallocation because of pointers. It's also utilized in function pointers and polymorphism.

Call by Pointer:

A function's address is copied into a formal parameter when arguments are passed to it using the call-by-pointer method. The address is used inside the function to determine the actual parameter used in the call. The passed argument is affected by modifications made to the parameter, in other words.

Argument pointers are supplied to functions the same way as other values to transmit values by the pointer. Since the following function swap() swaps the values of the two integer variables pointed to by its arguments, you must specify the function parameters as pointer types.

Due to the fact that both variables' addresses are the same, the variable inside the function is an alias for the variable that was supplied. As a result, any changes made to the variable within the function will likewise be reflected in the calling function.

A function that has the capacity to reflect changes may return more than one value. Additionally, this technique might theoretically allow a void function to return a value or several values. Values passed through the pass-by-pointer in a function are indicated by the & (address of) operator in the actual arguments.

Function Call by Pointer:

The term "call-by-pointer" refers to a technique where the variable address from the calling function is passed and used as a pointer inside the function.

Using this way, functions where the given variables' values could change are more clearly seen.

Specifically, with a pass-by-reference implementation, the function call does not contain any information that could be exploited to infer that the supplied variables' values might change during its execution (as the call is identical to call by value).

The address operator & is used in the function call when calling via a pointer, giving additional information about the function's purpose.

Program:

#include <iostream>
using namespace std;


// prototype for a function that takes pointers as parameters
void swap(int*, int*);


int main()
{


    // initialize variables
    int x = 12, y = 14;


    cout << "Before swapping" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;


    // calling a function with a variable address
    swap(&x, &y);


    cout << "\nAfter swapping" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    return 0;
}


//To swap numbers, here we define the function
void swap(int* a, int* b ) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

Explanation:

  • First, we created a swap function, which takes pointers as a function parameter. This function has void data types, which means this function is Returns Nothing type.
  • In the main() function, we initialize two variables, "x" and "y," which have an int data type.
  • Then we called the swap function with the address of the (&) operator.
  • Then We define the swap function for swapping the number.
  • When calling a function, the address of the variable is provided rather than the variable itself.
  • A dereference operator * must be used to access the value stored in the address since it is being passed rather than the value.
  • The value kept at addresses a and b, respectively, is given by the functions *a and *b.
  • Because a and b hold the addresses for x and y, any changes made to *a and *b will alter the actual values of x and y. Due to this, the values are altered when we print the values of x and y in the main() function.

Program output:

Call by Pointer in C++

Program:

#include <iostream>
using namespace std;


// Function define


void fun(int *a)
{
*a = *a - 1;
}




int main()
{
int x = 5;
cout << "Value of x before modification:  "<< x << endl;


// function call
fun(&x);
cout <<"Value of x after modification:  "<< x << endl;
}

Explanation:

  • 1st we define a function whose name is "fun" with the return type void and takes in value as a pointer. Here pointer (*) is denoted by an asterisk sign in the formal parameter.
  • In the fun() function body, the value of the formal parameter(*a) is decreased by 1.
  • In the main() function, we initialize a variable "x" with the value of 5, which has an int data type.
  • The execution will start from the main() function, the line "value of x before modification" will execute first, and the value of x will display.
  • Then the fun() function called the address of the variable is passed as an argument, and inside the function, the value of pointer a will decrease by 1.
  • Then the execution of this function will finish and execution takes back to the main() function.
  • And upon returning from the function, “the value of x after modification” will display, which turns out to be 1 less than the original value.

Program Output:

Call by Pointer in C++

Conclusion:

  • Call-by-pointer is quick and effective even when passing huge data items because a pointer or address' size is tiny and fixed (for instance, the size of a pointer to an int is the same as the size of a pointer to an enormous structure).
  • Programs can use the arguments to pass data into and out of functions using call-by-pointer technology (i.e., data can flow into the function, out of the function, or flow in both directions).
  • In C++, a call by the pointer is a technique for passing values to function parameters. When using a pointer to call a function, the formal parameter receives the address of the actual arguments. This means that if the values inside the function are changed, the actual parameters will also be affected.

Related Topics

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.