VOOZH about

URL: https://www.geeksforgeeks.org/cpp/when-do-we-pass-arguments-by-reference-or-pointer/

⇱ When do we pass arguments by pointer? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

When do we pass arguments by pointer?

Last Updated : 8 Jan, 2024

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 cases:

1. To Modify Local Variables of the Function

A pointer allows the called function to modify a local variable of the caller function.

Example

In the below example program fun() can modify the local variable x of main(). 


Output
New value of x is 20

2. For Passing Large-Sized Arguments

If an argument is large, the pass-by pointer is more efficient because only an address is really passed, not the entire object.

Example

The below example demonstrates the use pass-by pointer for passing large-sized arguments. consider the following Employee class and a function printEmpDetails() that prints Employee details.


Output
Name: geek
Designation: Software Engineer

The problem with the above code is that every time printEmpDetails() is called, a new Employee object is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a pointer.


Output
Name: geek
Designation: Software Engineer

Note This point is valid only for struct as we don't get any efficiency advantage for basic types like int, char, etc. 

3. To Achieve Run Time Polymorphism in a Function

We can make a function polymorphic by passing objects as a pointer to it.

Example

In the below program, print() receives a pointer to the base class object. Function print() calls the base class function show() if the base class object is passed, and the derived class function show() if the derived class object is passed.  


Output
In base
In derived

4. To Return Multiple Values

When you want to return multiple values from a function, passing pointers as function parameters allows us to modify the values of variables passed to the function.

Example


Output
Sum is: 12 
Product is: 35

5. To Modify the Content of Dynamically Allocated Memory.

By passing arguments by pointer to a function we can do modification in the content of dynamically allocated memory. It is mainly used when you want to allocate memory dynamically (by using functions like malloc, calloc, or realloc.

Example


Output
Dynamic value set is: 20

As a side note, it is a recommended practice to make pointer arguments const if they are being passed by pointer only due to reason no. 2 mentioned above. This is recommended to avoid unexpected modifications to the objects.

Comment
Article Tags: