Page 1 of 1

C; pass by value const argument

Posted: July 30th, 2004, 2:42 pm
by Mircea
I notice that in GSL (GNU Scientific Library in C) there are a lot of functions declarations that pass by value const arguments.What is the advantage to use a declaration as Func ( const double x );instead of Func ( double x );?

C; pass by value const argument

Posted: July 30th, 2004, 2:52 pm
by gc
Some programmers believe that the code should be as self explanatory as possible. I've worked with a (very talented programmer) who would have used that declaration, to make it clear that the value "x" wouldn't have been modified not even by the function itself. Pedantic, probably, his approach was useful, since it allowed the compiler to pick some otherwise silly mistakes. Even for one liners functions (where you are not really worried about making mistakes), he would keep the same declaration for style consistency.gcP.S. Mircea.... like the sciaman?

C; pass by value const argument

Posted: July 30th, 2004, 4:22 pm
by daveangel
there is a good reason to preferfunc(const double &x) instead offunc(double x).in the former, x is passed by referemce in the latter a copy is made of x. If x were a large blob rather than a double then its more efficienet to pass a reference (pointer) to it than to copy it. Also, by declaring x as const, you can be sure that ist not going to get modified on return.

C; pass by value const argument

Posted: August 1st, 2004, 12:22 am
by LTrain
Defensive coding practices are a good reason to declare a variable const. The full life cycle of a software object is rarely known. The next poor slob who puts their fingers in the code might modify the workings of the method or a related object. Illegal changes, like assigning a value to a const variable, is flagged immediately instead of causing bugs to propagate.

C; pass by value const argument

Posted: August 1st, 2004, 12:24 am
by LTrain
>> func(const double &x) Yes yes.. IMHO this style declaration should always be used when simply passing information to a method: very efficient, good defensive practice.