473,403 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

When to initialize the local variables?

Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.

Eg:

void func()
{
int i =0;

/* Some code follows */
i = <actual_value_of_i>;
}
2) Just before their use.

Eg:

void func()
{
int i;

/* Some code follows */
i = <actual_value_of_i>; /* "i " is initialized now */
}

Please advice.

Thanks,
Sriram.

Nov 30 '06 #1
21 8056
MQ

Sriram Rajagopalan wrote:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.

Eg:

void func()
{
int i =0;

/* Some code follows */
i = <actual_value_of_i>;
}
2) Just before their use.

Eg:

void func()
{
int i;

/* Some code follows */
i = <actual_value_of_i>; /* "i " is initialized now */
}

Please advice.

Thanks,
Sriram.
It doesn't matter when you initialize a variable, as long as you do NOT
read the variable and use it's value before it is initialized. The
second case is probably the best, since in the first case you are
initializing i twice, which is redundant. Not that this really matters
anyway, since the compiler would optimize such redundancy out most
likely. However, if you know the value of i at the point of
declaration, why not do it at that point? It really is a matter of
taste and also depends on the situation.

MQ

Nov 30 '06 #2
Sriram Rajagopalan wrote:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.

Eg:
void func()
{
int i =0;
/* Some code follows */
i = <actual_value_of_i>;
}

2) Just before their use.

Eg:
void func()
{
int i;
/* Some code follows */
i = <actual_value_of_i>; /* "i " is initialized now */
}

Please advice.
Method 1. leads to safer code, method 2. leads to negligibly faster
code. Method 2. might lead to negligibly more readable code, or might
not, depending on the programmer's tastes.

Nov 30 '06 #3
Sriram Rajagopalan wrote:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.

Eg:

void func()
{
int i =0;

/* Some code follows */
i = <actual_value_of_i>;
}
2) Just before their use.

Eg:

void func()
{
int i;

/* Some code follows */
i = <actual_value_of_i>; /* "i " is initialized now */
}

Please advice.
("Advi/s/e". Advice is what gets given; advise is what gets done.)

Neither of the above examples.

(3) When they are declared, in their declaration, to their actual value.

void func()
{
int i = <actual value of i>;
}

This is easiest in C99, which had a sudden attack of sanity and allowed
declarations after statements, but even in C90 you can get pretty close
to this without uglifying your code [1]. Then it's only the exceptional
cases that need thinking at read-time.

[1] Too much.

--
Chris "subtle, like a barrel" Dollin
"I'm still here and I'm holding the answers" - Karnataka, /Love and Affection/

Nov 30 '06 #4
santosh wrote:
Method 1. leads to safer code, method 2. leads to negligibly faster
code. Method 2. might lead to negligibly more readable code, or might
not, depending on the programmer's tastes.
Method 1 == stupid if your function has [say] 15 auto variables.

I give you for instance

int ccm_memory(int cipher,
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction)
{
unsigned char PAD[16], ctr[16], CTRPAD[16], b;
symmetric_key *skey;
int err;
unsigned long len, L, x, y, z, CTRlen;
....

There are 12 autos (most of which are re-used throughout the protocol,
hence the really specific names like "x" and "y"). Adding a default
initializer to all of them is a pain in the arse and would end up with
code like

unsigned char PAD[16] = {0}, ctr[16] = {0}, CTRPAD[16] = {0}, b =
0;
symmetric_key *skey = NULL;
int err = CRYPT_OK;
unsigned long len = 0, L = 0, x = 0, y = 0, z = 0, CTRlen = 0;

Which isn't exactly easier to read, nor really safer.

If you want to avoid uninitialized reads, use a tool like valgrind.

Tom

Nov 30 '06 #5
Chris Dollin <ch**********@hp.comwrote:
Sriram Rajagopalan wrote:
Which of these two would be a better way of initializing the local
variables? and why?
Neither of the above examples.

(3) When they are declared, in their declaration, to their actual value.

void func()
{
int i = <actual value of i>;
}
Which is rarely actually possible, since most often the value of one
initialiser depends on a computation involving another, or even on user
input.
This is easiest in C99, which had a sudden attack of sanity and allowed
declarations after statements,
Leading to maintenance programmers having to grope through your code to
find out where you hid the declarations this time. No, thanks.

Richard
Nov 30 '06 #6
Richard Bos wrote:
Chris Dollin <ch**********@hp.comwrote:
>Sriram Rajagopalan wrote:
Which of these two would be a better way of initializing the local
variables? and why?
>Neither of the above examples.

(3) When they are declared, in their declaration, to their actual value.

void func()
{
int i = <actual value of i>;
}

Which is rarely actually possible, since most often the value of one
initialiser depends on a computation involving another, or even on user
input.
I can't speak for your code, of course, but in what C code I write,
it's /usually/ possible, as in, most of my (auto) declarations have the
variables given their proper initial working values.

It doesn't matter if an initialiser depends on the value of another
variable: that just means the declarations have to be in the
right order. (The corresponding statements in the declare-then-assign
idiom have to be in the right order, so this isn't an onerous requirement.)
It doesn't even matter if they depend on user input (since that gets
abstracted out into functions).
>This is easiest in C99, which had a sudden attack of sanity and allowed
declarations after statements,

Leading to maintenance programmers having to grope through your code to
find out where you hid the declarations this time. No, thanks.
If the functions are big enough to need groping, the maintenance
programmer already has problems. A forest of uninitialised
declarations at the top of functions (or blocks) is equally opaque.
IMAO.

I wonder what the differences are in coding approach that lead to
these differing attitudes?

--
Chris "subtle, like a barrel" Dollin
"Our future looks secure, but it's all out of our hands"
- Magenta, /Man and Machine/

Nov 30 '06 #7
Sriram Rajagopalan wrote:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.
[...]
>
2) Just before their use.
It depends. This is mostly syntactic sugar, but it can (IMHO) make code
more readable and understandable. For example, if I have a typical "one
entry, one exit" function, I often set the variable the holds the exit
value right up front with some sensible default. This tells the reader
that if the function "falls through" it will be set to some default.

Conversely, when I'm using a variable used as a temporary or iterator
which must be reset to some value, I usually set/reset it just before use.

If a variable is just going to be clobbered by some function return, I
never initialize it. [An aside for the gurus: can the compiler optimize
away a spurious initializations? I'm thinking of a case where an
initializer once made sense, but then the next use of the variable is a
holder for a function return. Will some compilers know to optimize the
initialization?]
Nov 30 '06 #8
Sriram Rajagopalan said:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.
<snip>
>
2) Just before their use.
Well, you now know from reading the other responses that 1) is stupid and 2)
is stupid. You've been shown a 3) which is, naturally, stupid. And yet it's
hard to imagine a 4), isn't it?

So you have to make a judgement call.

Let's wrap up (3) into (1), since they are basically the same - i.e. "give
it the best you've got, at definition time". So:

Method 1 - initialise all auto objects to some default value unless their
proper starting value is actually known at definition time. This has the
advantage that, in the event of your (incorrectly) using a value before its
proper starting value has been calculated, the behaviour of the program is
deterministic and therefore easier to debug.

Method 2 - leave auto objects in an indeterminate state until their proper
starting value is known. This has the advantage, on some implementations,
that incorrectly using an indeterminate value may, if you are fortunate,
lead to the program "crashing", "segfaulting", "coredumping",
"access-violating", or call it what you will, leading to early detection -
but this is far from guaranteed. It has the further potential advantage of
being microscopically faster. Furthermore, *some* (but not all) compilers
can detect *some* (but not all) usages of indeterminate values, giving a
touch of reassurance which may or may not comfort you.

Which you choose is up to you. Personally, I favour Method 1, but I
recognise that there are some genuinely expert programmers in this
newsgroup who prefer Method 2. I respect their choice, and they respect
mine. Both approaches are valid, and to some extent your choice will depend
on other aspects of your programming style (for example, whether your
functions are typically short or long!).

Like I said, it's a judgement call. It is not as clear-cut as some of the
other responses have suggested.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 30 '06 #9
Sriram Rajagopalan wrote:
>
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.
2) Just before their use.
I prefer to initialize just before use.

I'm accustomed to compilers that warn of unused variables.
My preference is to not have unused variables remaining in the code.

"1) At the time of their declaration" silences the warning,
so I prefer to initialize just before use.

--
pete
Nov 30 '06 #10
pete wrote:
Sriram Rajagopalan wrote:

Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.
2) Just before their use.

I prefer to initialize just before use.

I'm accustomed to compilers that warn of unused variables.
My preference is to not have unused variables remaining in the code.

"1) At the time of their declaration" silences the warning,
so I prefer to initialize just before use.
/* t2.c */
#include <stdio.h>

int main(void) {
int a = 5, b, c = 10;

while(c < 20)
printf("%d\n", c);

return 0;
}
/* end */

$ gcc -Wall -Wextra -ansi -pedantic -o t2 t2.c
t2.c : In function: 'main'
t2.c:4: warning: unused variable 'b'
t2.c:4: warning: unused variable 'a'
$

Nov 30 '06 #11
Richard Heathfield wrote:
>
.... snip ...
>
Method 1 - initialise all auto objects to some default value unless
their proper starting value is actually known at definition time.
This has the advantage that, in the event of your (incorrectly)
using a value before its proper starting value has been calculated,
the behaviour of the program is deterministic and therefore easier
to debug.
Alternatively, it postpones the eventual blow-up to a remote
statement, and thus conceals the cause of the bug. Alternative
two, the faulty initialization never causes a blow-up, but simply
creates bad output. This is not detected for three years, after
having caused twenty-eight unnecessary deaths. Alternative three,
the extra initialization defeats the systems default trap value
initialization, preventing early detection and correction.
>From which you may gather that I am not a fan of shotgun
initialization.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

Nov 30 '06 #12
In article <11**********************@n67g2000cwd.googlegroups .com>,
Sriram Rajagopalan <bg*******@gmail.comwrote:
>Which of these two would be a better way of initializing the local
variables? and why?
I wouldn't give a hard-and-fast rule, but here are some considerations
I haven't seen mentioned elsewhere in the thread:

(1) don't initialise variables if the value is never used. For example,
don't do this:

int val = 0;
... lots of code not using val ...
val = f(...);

The initialisation will just confuse a reader who wonders what it's
used for.

(2) if you have to violate (1) explain why. For example, if you want
to avoid a compiler warning when the compiler suspects,
incorrectly, that a variable is used uninitialised, put a comment
by the initialisation:

void *p = 0; /* because gcc thinks it's used uninitialised */

(3) if you can't initialise one of a group of related variables, don't
initialise any. For example, don't do this:

int start=1, step, end;
...
step = f(...);
end = g(...);
for(i=start; i<end; i+=step)
...;

Instead assign to start before the loop. It's annoying to have to
look at two places to find information that belongs together.

(4) don't initialise a variable that you re-use, and have to
"reinitialise". For example, don't do this:

Link *p = head;
...
while(*p)
...;
p = head;
while(*p)
...;

It creates a spurious non-symmetry between the two uses, obscuring their
similarity.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Nov 30 '06 #13
Greetings,

Sriram Rajagopalan wrote:
Hi,

Which of these two would be a better way of initializing the local
variables? and why?

1) At the time of their declaration.

Eg:

void func()
{
int i =0;

/* Some code follows */
i = <actual_value_of_i>;
}
2) Just before their use.

Eg:

void func()
{
int i;

/* Some code follows */
i = <actual_value_of_i>; /* "i " is initialized now */
}
If you happen to be fortunate enough to use an implementation that will
flag `used before assigned' the second is better since the compiler will
let you know if you've made a logic error.

If not, the first is safer.

>
Please advice.

Thanks,
Sriram.

--
Kyle A. York
Sr. Subordinate Grunt
Nov 30 '06 #14
CBFalconer said:
Richard Heathfield wrote:
>>
... snip ...
>>
Method 1 - initialise all auto objects to some default value unless
their proper starting value is actually known at definition time.
This has the advantage that, in the event of your (incorrectly)
using a value before its proper starting value has been calculated,
the behaviour of the program is deterministic and therefore easier
to debug.

Alternatively, it postpones the eventual blow-up to a remote
statement, and thus conceals the cause of the bug.
Not so. We are all accustomed to back-tracking from a symptom to a cause,
are we not?
Alternative
two, the faulty initialization never causes a blow-up, but simply
creates bad output. This is not detected for three years, after
having caused twenty-eight unnecessary deaths.
Don't you ever test your programs?
Alternative three,
the extra initialization defeats the systems default trap value
initialization, preventing early detection and correction.
<shrugSuch errors are rare, easily spotted, and easily fixed. I think
you're making a moun-molehill-tain.
From which you may gather that I am not a fan of shotgun
initialization.
Hence your choice of terminology - "shotgun" indeed! :-)

Personally, I'm not a fan of undefined behaviour. Give me a *reproducible*
bug every time.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 30 '06 #15
kyle york writes:
If you happen to be fortunate enough to use an implementation that
will flag `used before assigned' the second is better since the
compiler will let you know if you've made a logic error.

If not, the first is safer.
Yes. Sometimes the compiler can't figure it out for sure though. In
case of gcc -Wall, it then warns that a variable _may_ be used
uninitialized.

I usually see if I can reorganize such code so gcc can tell that the
variable is initialized before use. E.g. for() -do..while(), or pick
one possible value as the default, or default:assert(0); in a switch().
Otherwise I may add a useless initialization just to silence the warning
- with a comment that it _is_ just supposed to to silence the warning.

--
Hallvard
Nov 30 '06 #16
I forgot one detail: The point isn't to initialize just before use if
you go that path, but to set the value around the place in the function
where it locically seems to belong. If there is such a place.

--
Hallvard
Nov 30 '06 #17
In article <Fz*****************@nnrp.ca.mci.com!nnrp1.uunet.c a>
Clever Monkey <cl**************@hotmail.com.invalidwrote:
>If a variable is just going to be clobbered by some function return, I
never initialize it. [An aside for the gurus: can the compiler optimize
away a spurious initializations? I'm thinking of a case where an
initializer once made sense, but then the next use of the variable is a
holder for a function return. Will some compilers know to optimize the
initialization?]
Given code like:

T var = initial;
... code that does not use var ...
var = result;

standard dataflow optimization techniques (there are several) will
all get rid of the redundant assignment. The initialization will
not disappear if you do something like this instead, though:

T var = initial;
... code that, while it does not use var, does use &var ...
var = result;

In this case, the use of "&var" can defeat attempts to follow the
points at which var is used and/or set. (If the address-of operator
can be removed by other optimizations, the dataflow techniques can
once again recover the points at which the variable is first used
and first defined, and remove the "= initial" part if it is in fact
redundant.)

Since C's arrays are generally turned into pointers internally,
most cases of:

T arr[N] = { initial };
... code that does not use arr[i] for any i ...
arr[i] = result; /* for some valid i */

are not optimized away except by particularly smart compilers.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 30 '06 #18
MQ

Chris Dollin wrote:
(3) When they are declared, in their declaration, to their actual value.
Surely this is not always possible, say, when the variable is
initialised by a call to a function. Think scanf()...

Nov 30 '06 #19
MQ

Chris Dollin wrote:
(3) When they are declared, in their declaration, to their actual value.
Surely this is not always possible, say, when the variable is
initialised by a call to a function. Think scanf()...

Dec 1 '06 #20
MQ wrote:
Chris Dollin wrote:
>(3) When they are declared, in their declaration, to their actual value.

Surely this is not always possible, say, when the variable is
initialised by a call to a function. Think scanf()...
Yes, it's not /always/ possible. But when it /is/ possible, I think it
is to be preferred.

As usual, clarity trumps everything [1] except user requirements.

[1] As you know, Bob, there are two trumps, either of which can be
a colour or a number.

--
Chris "Mu" Dollin
"Who are you? What do you want?" /Babylon 5/

Dec 1 '06 #21
Chris Dollin wrote:
>
.... snip ...
>
[1] As you know, Bob, there are two trumps, either of which can be
a colour or a number.
I believe there are more. Ivana, ... :-)

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

Dec 1 '06 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Bob Rock | last post by:
Hello, I was wondering when should static constructors be defined or are they even required??? Also, when are they implicitly called??? Bob Rock
4
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's...
18
by: vib | last post by:
Hi there, By chance, I came to learn that it is bad programming practice to initialize global variables at outside of programs. Is it that bad? In order to fullfil this, I had to declare them...
1
by: Jean Stax | last post by:
Hi ! A couple of pretty basic questions: Value types: As far as I understand, when I create value type without "new" syntax the object is considered as unutilized. Consequently, I have to...
10
by: Not Available | last post by:
On the host server: namespace JCart.Common public class JCartConfiguration : IConfigurationSectionHandler private static String dbConnectionString; public static String ConnectionString { get...
4
by: Dave | last post by:
I used the following class and .aspx code below to understand how static works on variables and methods taken from...
30
by: Javaman59 | last post by:
I come from a background of Ada and C++ programming, where it was considered good practice to explicitly initialize every variable. Now that I'm programming in C# I think that it would be best...
5
by: alingsjtu | last post by:
Hello, every body. When execute dynamic generated multiple OPENQUERY statements (which linkes to DB2) in SQLServer, I always got SQL1040N The maximum number of applications is already connected...
6
by: Ramon | last post by:
Is there a way to initialize the variables (or other data) of a header file by using a function (similar to main() function)?? Thankx
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.