Serving the Quantitative Finance Community

 
User avatar
Mircea
Topic Author
Posts: 0
Joined: July 9th, 2004, 6:04 pm

C; pass by value const argument

July 30th, 2004, 2:42 pm

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 );?
 
User avatar
gc
Posts: 10
Joined: September 21st, 2002, 10:08 pm

C; pass by value const argument

July 30th, 2004, 2:52 pm

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?
 
User avatar
daveangel
Posts: 5
Joined: October 20th, 2003, 4:05 pm

C; pass by value const argument

July 30th, 2004, 4:22 pm

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.
knowledge comes, wisdom lingers
 
User avatar
LTrain
Posts: 0
Joined: June 23rd, 2004, 6:42 pm

C; pass by value const argument

August 1st, 2004, 12:22 am

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.
 
User avatar
LTrain
Posts: 0
Joined: June 23rd, 2004, 6:42 pm

C; pass by value const argument

August 1st, 2004, 12:24 am

>> 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.