Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Initialize Variable

Status
Not open for further replies.

Warrioruw

Programmer
Jan 30, 2004
24
0
0
CA
Hi all,

This is just a simple question, and I hope you don't mind.

Is it a good idea to initialize variables?
For example,

double a; //if you don't initialize it, compiler will
//assign number such as -9.2559631349318e+061

For the concern of memory storage, I thought it might be a good idea to initialize it,

double a=0.0;


Please correct me if you have different opinion. Thanks
 
>Is it a good idea to initialize variables?

Yes!

/Per
[sub]
"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."[/sub]
 
I second that! ALWAYS initialized them. I have been bitten in the butt too many times by unitialized variables!

Matt
 
Definitely initialize variables, but not because it saves memory. Enough memory has to exist to hold any valid double anyway, regardless of whether you initialize it. The reason you should is to reduce bugs in your code. Besides, good C++ design includes not declaring variables until you can initialize them with the right data and are ready to use them. I'd suggest waiting until later in the code when you have an actual value to initialize it with.
 
Assign the values on declaration is not only a safe method of work by even results in better performance.

If I am not wrong, I saw this in Lipman C++ book.
 
A good example is working with pointers, not initialising them to NULL can be very bad

Code:
char* pszString;

if (pszString != NULL)
delete pszString; // This will corrupt the stack

char* pszString == NULL;
if (pszString != NULL)
delete pszString; // Wont even get here

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
Code:
char* pszString == NULL;
delete pszString; // Delete on NULL is perfectly safe unless its a delete []

/Per
[sub]
"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top