By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,825 Members | 1,255 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,825 IT Pros & Developers. It's quick & easy.

Variable declaration and initialisation

P: n/a
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

Jan 15 '06 #1
Share this Question
Share on Google+
22 Replies


P: n/a
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.

Jan 15 '06 #2

P: n/a
"James Brodie" writes:
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.
Jan 15 '06 #3

P: n/a
"relient" <xl***************@gmail.com> writes:
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.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 15 '06 #4

P: n/a
James Brodie wrote:
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 */
}

--
Eric Sosman
es*****@acm-dot-org.invalid

Jan 15 '06 #5

P: n/a
Keith Thompson wrote:

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.

--
Ian Collins.
Jan 15 '06 #6

P: n/a
<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

Jan 15 '06 #7

P: n/a
"relient" <xl***************@gmail.com> writes:
<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.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 16 '06 #8

P: n/a
James Brodie wrote:
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]; ++i) ;
ret i;
}

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

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jan 16 '06 #9

P: n/a
hi i am new to c
will you please tell me the wat is c89 and c99 series and how
they are different

Jan 16 '06 #10

P: n/a
raju wrote:
hi i am new to c
will you please tell me the wat is c89 and c99 series and how
they are different


See Question 11.1 in the comp.lang.c Frequently Asked
Questions (FAQ) list

http://c-faq.com/

--
Eric Sosman
es*****@acm-dot-org.invalid

Jan 16 '06 #11

P: n/a
On Mon, 16 Jan 2006 09:15:09 -0500, Eric Sosman wrote:
raju wrote:
hi i am new to c
will you please tell me the wat is c89 and c99 series and how
they are different


See Question 11.1 in the comp.lang.c Frequently Asked
Questions (FAQ) list

http://c-faq.com/


And an adjunct:
<http://clc-wiki.net/wiki/Basics_Of_The_C_Standard>

--
http://members.dodo.com.au/~netocrat

Jan 16 '06 #12

P: n/a
Netocrat said:
<http://clc-wiki.net/wiki/Basics_Of_The_C_Standard>


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!)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 16 '06 #13

P: n/a
On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:
Netocrat said:
<http://clc-wiki.net/wiki/Basics_Of_The_C_Standard>
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.

--
http://members.dodo.com.au/~netocrat
Jan 16 '06 #14

P: n/a
Netocrat said:
On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:
Netocrat said:
<http://clc-wiki.net/wiki/Basics_Of_The_C_Standard>
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.


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

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 16 '06 #15

P: n/a
On Mon, 16 Jan 2006 17:25:53 +0000, Richard Heathfield wrote:
Netocrat said:
On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:
Netocrat said:

<http://clc-wiki.net/wiki/Basics_Of_The_C_Standard>

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.


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.
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've just found where I first read this. Douglas Gwyn on 2 Nov 2005 in
comp.std.c wrote:
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.

--
http://members.dodo.com.au/~netocrat
Jan 16 '06 #16

P: n/a
Netocrat said:
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'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.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 16 '06 #17

P: n/a
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...

--
A+

Emmanuel Delahaye
Jan 16 '06 #18

P: n/a
Emmanuel Delahaye wrote:
James Brodie a écrit :
2) Should all variabled be initiailised immediately after declaration?


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.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jan 16 '06 #19

P: n/a
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.

--
A+

Emmanuel Delahaye
Jan 17 '06 #20

P: n/a


Emmanuel Delahaye wrote On 01/17/06 16:09,:
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.


And if you need to work with both p and q in the
same scope ...?

For example, if die() is "return an indication of
failure, e.g., -1 or NULL" (and the return type of f()
is suitably adjusted), the die() after the failure to
allocate memory for q would presumably want to free(p)
so as not to leak memory. What then?

We could go on making up examples and counter-examples
pretty much indefinitely, especially since neither point
of view is entirely unreasonable. (Mine is MORE reasonable
than yours, OF COURSE, harrumph, harrumph, but that's
another matter. ;-) However, the O.P.'s question was
2) Should all variabled be initiailised immediately
after declaration?


... and I think you'll agree that the word "all" calls
for the answer "No" from both the Usually-Initialize and
the Usually-Don't crowd.

(Strangest language I ever saw had an interesting way
of catching attempts to use uninitialized variables. They
were always accessed via indirection through a sort of
symbol table, and the compiler deliberately set the low-
order bits of the table's pointers so they'd be mis-aligned.
On a write, the code zeroed the pointer's low-order bit,
but on a read it simply used what the table contained.
Result: Try to read a variable before a write has repaired
its pointer, and you get a hardware trap. The run-time
would print a diagnostic message giving the name of the
variable and the line that performed the bad reference, and
then would initialize the variable to 1 and resume. Why 1?
Just in case the program was about to divide by it ...)

--
Er*********@sun.com

Jan 17 '06 #21

P: n/a

"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> wrote in message
news:43**********************@nan-newsreader-06.noos.net...
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.


Your code is most definately not the equivalent of Eric's.
His is meant to perform further work with the dynamically
allocated memory segments and I'm sure they'll later be
freed in the section left out (specified by the elipses).
Yours created 2 memory leaks! :-)
Jan 17 '06 #22

P: n/a
Mark B a écrit :
Your code is most definately not the equivalent of Eric's.
His is meant to perform further work with the dynamically
allocated memory segments and I'm sure they'll later be
freed in the section left out (specified by the elipses).
Yours created 2 memory leaks! :-)


Ahem... say "the ellipses was misplaced", huh...

--
A+

Emmanuel Delahaye
Jan 21 '06 #23

This discussion thread is closed

Replies have been disabled for this discussion.