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



C++ Structures

In the C/C++ programming language, the structure is user-defined data types that allow us to store the combination of different data types together. All the …
Read More

C++ Static Keyword

Static s a keyword in C++ that is when used with different types gives different meanings. static keyword can be used with variables in a …
Read More

C++ Templates

Templates in C++ are the powerful feature that allows us to write generic programs (generic classes and generic functions). A single class or function is …
Read More

C++ Friend Function

There are private and protected members in a class that is inaccessible from outside of the class, constituting one of the concepts of object-oriented programming …
Read More

this Pointer in C++

In C++, this is a keyword that refers to the current instance of a class and this pointer holds the address or points to the …
Read More

Inheritance in C++

Inheritance is one of the most important concepts of object-oriented programming. In C++, inheritance is the process of deriving the properties and behaviors of one …
Read More