"John Harrison" <> wrote in message news:<c5ml3o$3g2vb$>...
> "pembed2003" <> wrote in message
> news: om...
> > Hi coders,
> > I have the following:
> >
> > void f1(char* &s){
> > *s = 'a';
> > }
> >
> > void f2(char* s){
> > *s = 'b';
> > }
> >
> > int main(int argc,char** argv){
> > char a[] = "1234";
> > char* b = a;
> > printf("%s\n",a);
> > f1(b);
> > printf("%s\n",a);
> > f2(b);
> > printf("%s\n",a);
> > return 0;
> > }
> >
> > The above prints:
> >
> > 1234
> > a234
> > b234
> >
> > My question is:
> >
> > 1. How is char*& different from char* since they both do the same thing?
>
> They both do the same thing in your code, that doesn't mean they do the same
> thing always.
>
> > 2. When do you use the first form and the second form?
>
> When you pass by reference you pass a reference to the original object to
> your function, when you pass by value you get a copy of the original object.
> There are many different reasons for preferring one over the other.
>
> Here's one example
>
> void f1(char* &s){
> s = "a";
> }
>
> void f2(char* s){
> s = "b";
> }
>
> int main()
> {
> char* s = "c";
> cout << s << '\n';
> f2(s);
> cout << s << '\n';
> f1(s);
> cout << s << '\n';
> }
>
> Try running that and see what difference the reference makes.
>
> john
Good example. I think I understand it. In f2(), s is a local
automiatic variable, when you say 's = "b";', this local variable is
modified. In f1(), s is a reference to main's s so when you say 's =
"a";', main's s is also changed.
|