c++ pointer and function

Call by reference: using pointer

In this article, you will learn about passing the pointer as an argument to the function and effectively use in the c++ program.

How to use pointers as parameter in the function?


First of all, learn the concept of call by reference in the c++ function article. In this method, the argument passed in the function pass by value. Actually,in the pass by value copy of the variable value created in the function that's why called pass by value.


There is another to pass an argument to the function pass by reference. In this method alias of the variable is created in the function, not a copy of the variable would be created in the function. For getting knowledge about the call by reference.

In the passing of pointers as argument call by reference method is used.

For Example

#include <iostream>
using namespace std;
int average(int &,int &);
int main() {

int a=5;
int b=9;

int aver;
aver=average(a,b);//call the function of average
cout<<aver<<endl;


return 0;

}

int average(int &number1,int &number2)
{
int average;

average=(number1+number2)/2;//add first and 2nd variable value then divide by 2

return average;
}

Output

7


In this example, declare and initialize two variables in the main() function. Pass these two variables during the calling of the average function.In the definition of the average function accept the two-argument and add these two variables then divide by 2.


After that average variable return in the end of the function. This two-argument pass by the reference and alias create in the function.


Passing by the reference using pointer




For Example:Pass by reference using pointers

#include <iostream>
using namespace std;
int average(int *,int *);
int main() {

int a=5;
int b=9;

int aver;
aver=average(&a,&b);//call the function of average
cout<<aver<<endl;


return 0;

}

int average(int *number1,int *number2)
{
int average;

average=((*number1)+(*number2))/2;//add first and 2nd pointer value then divide by 2

return average;
}

Output

7

In the example, two pointers are used as the two-argument in the function. The average function has two arguments as pointers. Pass by reference, the address of the two variable passes during the calling of the average function.

In the definition of the function, deference the pointer for getting the value of the arguments,Then add both arguments and find the average.

Comments

Popular posts from this blog

Flutter layout

Diferrence between flutter and react native

how to cout in cpp