Coding style point: "const" in function parameter declarations

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Kevin Grittner <Kevin(dot)Grittner(at)wicourts(dot)gov>, Dan Ports <drkp(at)csail(dot)mit(dot)edu>
Cc: pgsql-hackers(at)postgreSQL(dot)org
Subject: Coding style point: "const" in function parameter declarations
Date: 2011-06-21 22:51:20
Message-ID: 10898.1308696680@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

I notice that the SSI code is rather heavily invested in function
declarations like this:

extern bool PageIsPredicateLocked(const Relation relation, const BlockNumber blkno);

I find this to be poor style, and would like to see if there's any
support for getting rid of the "const" keywords. My objections are
twofold:

1. What such a "const" marking actually does is to forbid the function
from changing the value of its local variable that received the passed
parameter value. While you may or may not think that it's good style
to avoid doing so, whether the function chooses to do that or not is
surely no business of its callers'. Putting such a marking into the
extern declaration doesn't create any useful API contract, it just means
you'll have to change the declaration if you change the function's
implementation.

2. In cases such as "const Relation foo" where the parameter type is
a typedeffed pointer, it is easy for readers to arrive at the false
conclusion that this guarantees the function doesn't change the
pointed-to structure. But it guarantees no such thing, because that
construction is *not* equivalent to "const struct RelationData *foo";
rather it means "struct RelationData * const foo", ie only the pointer
is being const-ified, not that to which it points. The function can
hack the struct contents, or pass the pointer to functions that do
arbitrary things, and the compiler won't make a whimper. So I think
that declarations like this are positively pernicious --- they'll
mislead all but the most language-lawyerly readers.

Declarations like "const structtype *param" are fine, because those
create a real, enforced contract on what the function can do to data
that is visible to its caller. But I don't see any value at all in
const-ifying the parameter itself.

Comments?

regards, tom lane

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Mark Kirkwood 2011-06-21 23:13:12 Re: Re: patch review : Add ability to constrain backend temporary file space
Previous Message Robert Haas 2011-06-21 22:38:29 Re: Fwd: Keywords in pg_hba.conf should be field-specific