Michael Chesterton wrote:
> void init(foo &p, const int x, const int y)
> {
> p.x = x;
> p.y = y;
> }
>
> Do people do that in practice?
No, not for ints, bools floats etc, but yes for pointers.
> Is it good practice?
Yes for pointers, no for everything else.
You need to remember that in C and its decentants, parameters
are copied when they are passed to functions. Try this:
void change_param (int a, bool b)
{ a++ ;
b = ! b ;
}
int main (void)
{
int a = 10 ;
bool b = false ;
change_param (a, b) ;
printf ("a = %d, b = %s\n", a, b ? "true" : "false") ;
return 0 ;
}
If you run this, you will find that the values of a and b in the main
function are unchanged from their original values. That because when
they are passed to a function, a copy is made of each and the copy is
passed.
The same thing applies to pointers, the pointer is copied and passed
to the function. However in the function the pointer can be
de-references and the dereferenced value modified. Const can prevent
this. Finally, remember than in C, strings are just pointers to arrays
of char.
> void init(foo &p, const int x, const int y)
Ok, here you have a reference, so you're obviously using C++
instead of C. References in C++ are just pointers with slightly
different syntax.
Now that you have been told all this, I suggest you write yourself
a program to test all the possibilities for yourself. C and C++
behaviour will help reinforce the concepts.
HTH,
Erik
--
-----------------------------------------------------------------
Erik de Castro Lopo
-----------------------------------------------------------------
"Every time an American goes to a gas station, he is sending money
to America's enemies." -- http://www.meforum.org/article/653
_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders