[petsc-dev] declaring argument as const basic type in PETSc

Chetan Jhurani chetan.jhurani at gmail.com
Wed Aug 17 14:04:00 CDT 2011


> From: Jed Brown
> Sent: Wednesday, August 17, 2011 12:38 PM
> To: For users of the development version of PETSc
> Subject: Re: [petsc-dev] declaring argument as const basic type in PETSc
> 
> On Wed, Aug 17, 2011 at 11:34, Barry Smith <bsmith at mcs.anl.gov> wrote:
> > But my question remains, should we const declare function arguments?
> 
> No, the prototype should never use const for stack arguments (pointer to const
> is totally different and should be used anywhere that it is correct).
> 
> I don't know any responsible libraries that const-ify value parameters in
> prototypes. I think it most commonly arises from ignorance of, or sloppiness
> with, the actual semantics of the C language.


It is useful to have const pass-by-value parameters in function
definitions.  Not useful in the function declarations or for the
caller.

This is so that a developer does not assign to a passed-in int 
unintentionally.  Almost all C and C++ compilers accept it and they
error out if one does something like the code below.  An exception
is old IRIX compilers that emit a warning on using const pass-by-value
and said it is meaningless to use them.  I disagree.

void f(const int n, int* j)
{
    *j = n;
    n = 0; // error
}

Of course it is more useful for preventing bugs in more complex
functions.

Chetan





More information about the petsc-dev mailing list