C++ Passing Pointers to Functions3 min read

A function is a user-defined block of codes that executes some specific task assigned to it invoked by its name. If there is an argument to be passed while calling a function then it is called actual arguments. There are two ways to call a function:

  • call by value
  • call by reference

In a first way, we pass the actual values as an actual argument and those values are copied to the function and the function does some task with them. And the second way to call a function can be processed in two ways:

  • by passing the references
  • by passing the pointers

In C++ programming, just like we pass values of the variable as parameters in the function, we can also pass addresses as an argument in functions.

When we pass pointers in the function that means we pass the address of the variable instead of the value.

Let us understand it through a syntax.

As you can see that the func() function takes a reference of the number variable that is the address of the number. And & is used to access the address.


Example: Passing Pointer to Function by reference

Output: After execution of the above code, you will get the following result.

In the above program, we use * in the swapFunc() function with passing reference to swap the number because we are dealing with the address so it is necessary to put * while using those variables.


Return Pointer from Functions

As we know, in C++ that array can be returned from the function, similarly, a pointer can also be returned from a function. For this, we need to declare the returning function as the pointer in the following way.

Also, note that it is considered bad practice to return the address of a local variable from a function, so define the local variable as a static variable.

Now let us see an example

Output:


MORE

Implement Insertion sort Program in C

In this tutorial, we will learn and write a C program to implement insertion sort. Before that you may go through the following topics in …
Read More

C Program for implementation of Selection sort

In this tutorial, we will learn and write a C program to implement selection sort using function. Before that you may go through the following …
Read More

C Program to Delete a Particular element from an Array

In this tutorial, we will write a C program to delete an element in an array by specifying the value. Before that, you should have …
Read More

C Program to sort a String in Ascending order

In this tutorial, we will write a c program to sort a string array in ascending order. Before that, you may go through the following …
Read More

C Program to find Maximum occurring Character in a String

In this tutorial, we will write a program in C to find the maximum occurring character in a string. Before that, you may go through …
Read More

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More