Variable declaration and initialisation

J

James Brodie

I just wanted to get some advice on what are the better practices:

1) Should variables be declared at the beginning of a function or just
before they are required?

2) Should all variabled be initiailised immediately after declaration?

Thanks
 
R

relient

1.) Well, in c89 you don't have a choice. You must declare all your
variables the the begining of the scope block. In c99, however, it's
different. It's up to you to choose the best method, but, be
consistent.

2.) For safety reasons, you should, especially pointers. If you declare
a poiner and don't intialize it to some non-null value; inititiaze it
to null to avoid unwanted bugs in your code.

That's my take on it.
relient.
 
O

osmium

James Brodie said:
I just wanted to get some advice on what are the better practices:

1) Should variables be declared at the beginning of a function or just
before they are required?

They should be declared just before needed. The common form of C does not
allow this, so it's a bit academic.
2) Should all variabled be initiailised immediately after declaration?

No. It just creates one more question in the mind of the person who must
maintain the program. Why did he set this to 0? It creates an illusion of
knowledge that doesn't exist.
 
K

Keith Thompson

relient said:
1.) Well, in c89 you don't have a choice. You must declare all your
variables the the begining of the scope block. In c99, however, it's
different. It's up to you to choose the best method, but, be
consistent.

Even in C89/C90, you can declare variables at the beginning of any
block, not just at the beginning of a function. For example:

void func(void) {
/* code that doesn't use x */
{
int x;
/* code that uses x */
}
/* more code that doesn't use x */
}
2.) For safety reasons, you should, especially pointers. If you declare
a poiner and don't intialize it to some non-null value; inititiaze it
to null to avoid unwanted bugs in your code.

On the other hand, I see a lot of code that initializes a variable,
and then assigns a value to it before using it. A policy of *always*
initializing every variable, whether the initial value is used or not,
can avoid errors, but it's not always necessary.

Also, it's important to provide some context when posting a followup.
Google makes this unnecessarily difficult, but not impossible. See
<http://cfaj.freeshell.org/google/> for details.
 
E

Eric Sosman

James said:
I just wanted to get some advice on what are the better practices:

1) Should variables be declared at the beginning of a function or just
before they are required?

Under C89 rules, variable declarations in a block
must precede all the executable statements at the same
nesting level. A function body is a block, so all the
"function-wide" variables must be declared at the top.
Note, though, that nested blocks within the function's
outermost block have their own scopes, and can contain
their own variable declarations:

void f(void) {
int x;
...
if (the_witch_is_dead) {
char message[] = "Ding, dong!";
puts (message);
...
}
...
{
double trouble;
trouble = sqrt(toil);
...
}
}

If you have a C99-conforming implementation, you can
mix variable declarations and executable statements, the
only requirement being that the declaration must precede
all the uses.
2) Should all variabled be initiailised immediately after declaration?

No. Initialize those that need initialization, and
leave the others alone. Under C99 rules, a case can be
made for postponing the declaration until a point at which
you know the first value that will be assigned to it, and
declaring and initializing the variable at that point.
Under C89 you might write

void f(void) {
int x;
/* statements not involving x */
x = g(z);
/* statements using x */
}

.... and under C99 this might be a little better as

void f(void) {
/* statements not involving x */
int x = g(z);
/* statements involving x */
}
 
I

Ian Collins

Keith said:
On the other hand, I see a lot of code that initializes a variable,
and then assigns a value to it before using it. A policy of *always*
initializing every variable, whether the initial value is used or not,
can avoid errors, but it's not always necessary.
It also prevents your compiler or lint from picking up unused variables.
 
R

relient

<quote>Keith Thompson:
Even in C89/C90, you can declare variables at the beginning of any
block, not just at the beginning of a function. For example:</quote>

That's what I meant by "You must declare all your variables at the
begining of the scope block." (notice I did not say function?) that
includes the begining of a function and a block which has scope from {
to } :p
 
K

Keith Thompson

relient said:
<quote>Keith Thompson:
Even in C89/C90, you can declare variables at the beginning of any
block, not just at the beginning of a function. For example:</quote>

That's what I meant by "You must declare all your variables at the
begining of the scope block." (notice I did not say function?) that
includes the begining of a function and a block which has scope from {
to } :p

Right, I was amplifying, not disagreeing.

BTW, the "<quote> ... "</quote>" syntax is better than nothing, but
please use Usenet standard of prefixing each quoted line with "> ".
See <http://cfaj.freeshell.org/google/> for details.
 
J

Joe Wright

James said:
I just wanted to get some advice on what are the better practices:

1) Should variables be declared at the beginning of a function or just
before they are required?

2) Should all variabled be initiailised immediately after declaration?

Thanks

It's taste and style. But first, you mean define, not declare. I still
write C89 and so I must define variables at the beginning of the block
before any function calls. C99 gives more lattitude as to where you can
place definitions.

I tend to initialize variables only as needed. For example..

int length(char *s) {
int i;
for (i = 0; s; ++i) ;
ret i;
}

...I don't initialize i on definition because the for statement does it.
 
R

raju

hi i am new to c
will you please tell me the wat is c89 and c99 series and how
they are different
 
R

Richard Heathfield

Netocrat said:

You might want to get someone to look over that in a bit more detail. I
spotted one error, which I've corrected (Kernighan was certainly a
co-author of "The C Programming Language", but could hardly be described as
a creator of the C programming language), but there could be more. (Jack
Klein is probably the guy to ask about ratification dates etc, since he
seems to delight in correcting people who get them wrong!)
 
N

Netocrat

Netocrat said:


You might want to get someone to look over that in a bit more detail. I
spotted one error, which I've corrected (Kernighan was certainly a
co-author of "The C Programming Language", but could hardly be described as
a creator of the C programming language),

Right, from what I understand Ken Thompson would better fit that title.
Was "K&R" as an unofficial standard defined by more than just the white
book though? - I understand that AT&T manuals as well as Steven C.
Johnson's reference C implementation contributed to the language's
definition.
but there could be more.
(Jack Klein is probably the guy to ask about ratification dates etc,
since he seems to delight in correcting people who get them wrong!)

Any corrections that he has for that page are welcome - it should be as
accurate as possible.
 
R

Richard Heathfield

Netocrat said:
Right, from what I understand Ken Thompson would better fit that title.

Try "Dennis Ritchie". I suspect dmr had much more input into Unix than kt
had into C. http://cm.bell-labs.com/cm/cs/who/dmr/chist.html is well worth
a read (and you might want to cross-refer to it from your site).

Was "K&R" as an unofficial standard defined by more than just the white
book though?

I've heard it told both ways. Ask an old fart. (I get my generic o.f. badge
in about a year from now, but my C-specific o.f. badge is going to be a few
more years a-coming.)
 
N

Netocrat

Netocrat said:

Try "Dennis Ritchie".

Oh, that goes without saying. I meant that Ken Thompson would better fit
the title of co-creator of C than Brian Kernighan, but rereading what I
wrote I see that it wasn't particularly clear, and as you write below, his
role may not have been as significant as to warrant that title (not having
been there at the time, I won't judge).
I suspect dmr had much more input into Unix than kt had into C.
http://cm.bell-labs.com/cm/cs/who/dmr/chist.html is well worth a read
(and you might want to cross-refer to it from your site).

Or you or any other c.l.c.er - it's intended as a group wiki, not a
personal site. But point taken, I'm aware of that article and it deserves
to be linked to from somewhere in the wiki - probably an "external links"
or "historical notes" page.
I've heard it told both ways. Ask an old fart.

I've just found where I first read this. Douglas Gwyn on 2 Nov 2005 in
comp.std.c said:
K&R(1) Appendix A was one of the main guides to C before there was an
official standard, but actual implementations of C did not accurately
follow the spec in that Appendix, and there were several generally
accepted changes to the language and library beyond what K&R described.
The AT&T C Reference Manual was considered by many to be more
authoritative.

<http://groups.google.com/group/comp.std.c/msg/0933afffda92e8f6>

It's not clear from this though whether the "generally accepted changes"
and/or those in the AT&T manual would form part of what we now, looking
back, refer to as "K&R C". I've come across descriptions that seem to
suggest one or more of "DMR's compiler for the pdp-11", "Johnson's PCC"
and "AT&T's compiler" could be thought of as reference implementations.
 
R

Richard Heathfield

Netocrat said:
I've just found where I first read this. Douglas Gwyn on 2 Nov 2005 in
comp.std.c wrote:

Well, if Doug said it, it's probably so. He certainly counts as an old fart,
if he'll forgive me for saying so; he is, after all, mentioned in
dispatches in K&R's acks section.
 
E

Emmanuel Delahaye

James Brodie a écrit :
I just wanted to get some advice on what are the better practices:

1) Should variables be declared at the beginning of a function or just
before they are required?

Yes, at the top of a block. The block bounds the scope of the object.
IMO, it's a Good Thing for objects and functions to have a reduced to
minimum scope.

It helps reading, maintenance and preapre the code for modularization.
It also forces the coder (and the compiler) to check the initialisation
and prevents against the uncontrolled reuse of an object (with a wrong
init value).
2) Should all variabled be initiailised immediately after declaration?

In most cases, yes, specially pointers. (NULL or their nominal value).

Special case:

int i;

for (i = 0; i < 10; i++)

is, IMO, better than a religious :

int i = 0;

for (; i < 10; i++)

but it's prpbably more a style issue...
 
E

Eric Sosman

Emmanuel said:
James Brodie a écrit :


In most cases, yes, specially pointers. (NULL or their nominal value).

In most cases, no. Here's an example of why not:

void f(void) {
char *p;
char *q;
p = malloc(strlen(string1) + 1);
if (p == NULL)
die();
strcpy (p, string1);
p = malloc(strlen(string2) + 1);
if (q == NULL)
die();
strcpy (q, string2);
...

Some compilers are able to detect and warn about the use
of uninitialized variables, and such compilers will catch
the error in the above code. If the two variables were
initialized to NULL (or whatever) at declaration, the
error would go unnoticed until run-time. The effect of
the initialization, then, is simply to defeat the compiler's
attempt to be helpful and to slow down the detection of
the error.
 
E

Emmanuel Delahaye

Eric Sosman a écrit :
In most cases, no. Here's an example of why not:

void f(void) {
char *p;
char *q;
p = malloc(strlen(string1) + 1);
if (p == NULL)
die();
strcpy (p, string1);
p = malloc(strlen(string2) + 1);
if (q == NULL)
die();
strcpy (q, string2);
...

Some compilers are able to detect and warn about the use
of uninitialized variables, and such compilers will catch
the error in the above code. If the two variables were
initialized to NULL (or whatever) at declaration, the
error would go unnoticed until run-time. The effect of
the initialization, then, is simply to defeat the compiler's
attempt to be helpful and to slow down the detection of
the error.
I understand your point, but I prefer to use a different coding
technique based on the reduction of the scope of functions and objects:

void f(void)
{
{
char *p = malloc(strlen(string1) + 1);
if (p == NULL)
die();
strcpy (p, string1);
}

{
char *q = malloc(strlen(string2) + 1);

if (q == NULL)
die();
strcpy (q, string2);
}
<...>

and magically, the bug did'nt happen at all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top