Re: Coding style question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: imad <immaad(at)gmail(dot)com>
Cc: "Gregory Stark" <stark(at)enterprisedb(dot)com>, korryd(at)enterprisedb(dot)com, pgsql-hackers(at)postgresql(dot)org
Subject: Re: Coding style question
Date: 2006-11-02 19:40:14
Message-ID: 19836.1162496414@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

imad <immaad(at)gmail(dot)com> writes:
> Well, its about the coding style. And I doubt there exists a data type
> which may not have
> an initializer. A NULL / Zero is an option in all cases and you can do
> whatever you want to assign it a value immediately after the
> initialization section. My two cents!

Actually, there are a lot of situations where putting an initializer is
definitely *bad* style in my opinion, because it can hide errors of
omission that the compiler would otherwise find for you. The most
common example you'll see in the Postgres code is variables that should
be set in each branch of an if or switch construct:

int val;

switch (foo)
{
case A:
val = 42;
break;
case B:
val = 52;
break;
...
default:
elog(ERROR, ...);
val = 0; /* keep compiler quiet */
break;
}

return val;

Someone might think it better to initialize val to 0 and get rid of the
useless (unreachable) assignment in the default case, but I say not.
With this structure, you'll get an uninitialized-variable warning if
you forget to set "val" in any one of the cases of the switch. That's
a check worth having, especially if the code is at all complicated
within the cases.

When the variable is going to be set anyway in straight-line code at the
top of the function, then it's mostly a matter of taste whether you set
it with an initializer or an assignment. But whenever there are
multiple places that might need to set it, I try to structure the code
to exploit the compiler's ability to catch uninitialized variables,
and that means not using an initializer.

regards, tom lane

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message korryd 2006-11-02 19:42:25 Re: Coding style question
Previous Message korryd 2006-11-02 19:23:18 Re: Coding style question