pointer in the function in c++with examples

Image result for c++Going forward with this C/C++ programming language tutorial we will know more about pointer.
See the example given below and think for a while what it will print. you may wonder to see the actual output.

#include <stdio.h>

void
add1(int i) {
i = i + 1;
}


int
main() {
int
x = 5;
printf("before adding x = %d \n", x);
add1(x);
printf("after adding x = %d \n", x);

scanf("%d", &x);
return
1;
}


It will give the following output when run.
before adding x = 5 
after adding x = 5
Now lets see why it gives this output. If you see add1 function, it is increasing value of parameter passed to it. In main value of x is 5 hence 1st time it prints x = 5 print. Then x is passed to add1 function, hence value of x should be increased by 1. but its value is still 5 hence 5 is printed again not 6.

Reason for this is that when ad1 function was called, it made separate copy of parameter x. add1 function changed value of copy, not original hence original x is still same.

When a is function called, a separate copy is made for all the parameters passed to it and that copy is given to called function. hence if called function changes values of parameters, it changes only copy, not original parameters.

Now see the C++ program given below which uses pointer and think what will be output.
#include <stdio.h>

void
add1(int* i) {
*
i = *i + 1;
}


int
main() {
int
x = 5;
printf("before adding x = %d \n", x);
add1(&x);
printf("after adding x = %d \n", x);

scanf("%d", &x);
return
1;
}

It will give the output -
before adding x = 5 
after adding x = 6
Now lets understand this why value value of x changes after function call. Here add1 function does not take int variable but address of int variable. It goes to that address that increases value stored at that address.
In main when add1 function is called, address of x is passed to it.As explained above, it will make copy of address of x that will be given to add1 function. If add1 function changes address given to it then value of x will not change but this function changes value stored in that address. Be it original address or copy of address, it will remain address of given variable, hence if we change value stored in address then value of original variable will also be changed
Later we will know more about pointer.