LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   output (https://www.linuxquestions.org/questions/programming-9/output-4175413822/)

mscoder 06-28-2012 07:27 AM

output
 
Code:

#include<stdio.h>
#include<iostream.h>
void fun(int *b)
{
 int c=5;
cout<<"value of pointer in fun()"<<"\n"<<b;
b=&c;
 (*b)++;
cout<<"the value of c is"<<*b;
}
int main()
{
int a=4;
int *p=&a;
cout<<"previous value of a  is "<<*p;
cout<<"value of pointer in main :"<<"\n "<<p;

fun(p);
cout<<"after calling fun ,new value of a is "<<*p;
return 0;}

...

how is the o/p remaining the same in main() even after we change the pointer's to point to another variable in func()??

NevemTeve 06-28-2012 07:38 AM

The parameter is passed by value, so this statement: 'b=&c' changes only the copied value, not the original.

PS: you really should use printf, it is much more flexible, eg:

Code:

printf ("main, beforore 'fun': a=%d, p=%p\n", a, p);

mscoder 06-28-2012 07:51 AM

Quote:

Originally Posted by NevemTeve (Post 4714077)
The parameter is passed by value, so this statement: 'b=&c' changes only the copied value, not the original.

PS: you really should use printf, it is much more flexible, eg:

Code:

printf ("main, beforore 'fun': a=%d, p=%p\n", a, p);

thanx.i thnk i get it..but jst to make sure when i change the argument to be passed as refernce, the o/p changes..so does this actually mean when we pass a reference to a variable,another copy of that reference is not created in func()??
Code:

#include<iostream.h>
void fun(int &b)
{
 int c=5;
 b=c;
 b++;
}
int main()
{
int a=4;
int &p=a;
cout<<"previous value of a  is "<<p;

fun(p);
cout<<"after calling fun ,new value of a is "<<p;
return 0;
}


NevemTeve 06-28-2012 09:16 AM

Yes, that's how call-by-reference is different to call-by-value.


All times are GMT -5. The time now is 06:10 PM.