10 Replies - 2124 Views - Last Post: 05 January 2010 - 01:32 AM Rate Topic: ***-- 2 Votes

#1 kenryuakuma   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 408
  • Joined: 14-December 08

Variable Initialization

Posted 02 January 2010 - 03:25 PM

well...This is small and simple question that most of the people might not even take into consideration or it is just being ignored. The question is the variable initialization. Of course, I know that it is a good habit or practice to initialize your variable as you declare, but some of the people said it is not really necessary. Whenever I don't initialize it when I declare the variable, my compiler always gives me a warning message, but sometimes it doesn't. What baffles me is how do we know when we don't have to initialize it when we declare a variable without being warned?

These two statements could generalize what I say.

int i;
int y;

i = 100;

Console.WriteLine("i = " + i);

y = i / 50;

Console.Write("i = {0}", y);

// We don't receive a warning message.



int i;
bool result;

Console.Write("Please enter your number: ");
result = int.TryParse(Console.ReadLine(), out i);

Console.WriteLine();

if(!result)   Console.Write("Invalid input");

Console.Write("Your number: {0}", i);

// We will receive a warning message about not initializing the variables.



Is This A Good Question/Topic? 1
  • +

Replies To: Variable Initialization

#2 Martyr2   User is online

  • Programming Theoretician
  • member icon

Reputation: 5357
  • View blog
  • Posts: 14,256
  • Joined: 18-April 07

Re: Variable Initialization

Posted 02 January 2010 - 03:43 PM

I have read many papers and done some research into this very topic and my conclusion is a very solid one... don't declare (and initialize) a variable until you actually need it. And if you decide you need it, you typically know its starting value so initialize it.

Often times you find a ton of people creating a laundry list of variables at the top of a function to then be used like 20 lines down in the code. The distance from the point where the variable is declared and where it is actually used is called the variables "lifespan" and measured in code lines. Many experts have suggested, with good reason, that you should keep this lifespan as short as possible. For instance, declaring a variable and using it 20 lines down means the variable (in that scope) is susceptible to corruption for 20 lines. The 20 lines in between may or may not inadvertently corrupt that variable's value and make it wrong or make it into something you didn't intend to happen. The second problem is one of maintenance. If I come in and alter the code that uses that variable's value, I have to zip up to the top of the function to delete it. I shouldn't have to do this. Instead, if you keep the lifespan small, the variable is declared close the code that uses it, shrinking the window in which something bad can happen to it as well as make it easier to find and remove/alter in the case I am doing something with the code later.

You are right in that people often ignore this, but it is because it is not often taught in school. As a general rule, I always recommend that you declare your variables close to where you intend to use them and only when you decide that you absolutely need it. If you decided you already need it, you typically know what its starting value is going to be. So I suggest you always initialize your variables for readability, to put them into a "known" state, and if you keep the lifespan small, protects you from unintended bugs.

For more information on this idea, read the book Code Complete 2 by Steve McConnell. This book is legendary and I find his whole section on this topic an excellent read. :)

This post has been edited by Martyr2: 02 January 2010 - 03:44 PM

Was This Post Helpful? 0
  • +
  • -

#3 kenryuakuma   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 408
  • Joined: 14-December 08

Re: Variable Initialization

Posted 02 January 2010 - 05:35 PM

Well...Thanks for the lifespan thing, and it is very well written, but I still don't understand why some of the variables, when declared, without giving them value and later use them, we don't receive a warning message about "uninitializing the variable", but in certain situation, we will receive this message, this is what I am looking for with a solid response.

WHY? According to what you say if it goes beyond the lifespan of the variable without giving it value or using them, the variable will be susceptible to corruption, but if you take my codes written in my previous post as an example, it is obvious that the variables are within the lifespan, in the first program I wrote, nothing happens, but the second program will generate error message.
Was This Post Helpful? 0
  • +
  • -

#4 ericode   User is offline

  • D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 112
  • Joined: 09-December 06

Re: Variable Initialization

Posted 03 January 2010 - 05:44 PM

View Postkenryuakuma, on 2 Jan, 2010 - 04:35 PM, said:

Well...Thanks for the lifespan thing, and it is very well written, but I still don't understand why some of the variables, when declared, without giving them value and later use them, we don't receive a warning message about "uninitializing the variable", but in certain situation, we will receive this message, this is what I am looking for with a solid response.

WHY? According to what you say if it goes beyond the lifespan of the variable without giving it value or using them, the variable will be susceptible to corruption, but if you take my codes written in my previous post as an example, it is obvious that the variables are within the lifespan, in the first program I wrote, nothing happens, but the second program will generate error message.


The compiler is smart enough to know if a variable has been initialized before you use it. It doesn't matter if that initialization occurs when you declare the variable or later. In the first code snippet you supplied, you were assigning values to your i and y variables before accessing them (i.e. printing their values). In the second code snippet, you assigned result before using that, so the compiler does not complain. Additionally, you've assigned a value to i (note that int.TryParse would assign a value of 0 to i if the user types in a string that is not a number), so the compiler does not complain again. Your comment about the compiler complaining about not initializing the variables was a falsehood. This code compiles without error or warning:
using System;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			int i;
			bool result;

			Console.Write("Please enter your number: ");
			result = int.TryParse(Console.ReadLine(), out i);

			Console.WriteLine();

			if (!result) Console.Write("Invalid input");

			Console.Write("Your number: {0}", i);
		}
	}
}


Was This Post Helpful? 0
  • +
  • -

#5 kenryuakuma   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 408
  • Joined: 14-December 08

Re: Variable Initialization

Posted 03 January 2010 - 05:53 PM

Oh really! I think there must be something wrong with my compiler or I must have posted the wrong code snippet...Sorry about that, and I will post the right one with error message maybe tomorrow or so.
Was This Post Helpful? 0
  • +
  • -

#6 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Variable Initialization

Posted 03 January 2010 - 06:04 PM

View Postkenryuakuma, on 2 Jan, 2010 - 04:25 PM, said:

well...This is small and simple question that most of the people might not even take into consideration or it is just being ignored. The question is the variable initialization. Of course, I know that it is a good habit or practice to initialize your variable as you declare, but some of the people said it is not really necessary. Whenever I don't initialize it when I declare the variable, my compiler always gives me a warning message, but sometimes it doesn't. What baffles me is how do we know when we don't have to initialize it when we declare a variable without being warned?


Yes, there are instances where the compiler will not compile your program when a variable is not initialized first. As one part of Martyr2's post said, I suggest you always initialize your variables for readability, to put them into a "known" state.

There is no reason why you would do the following but this will cause the error you are talking about, a variable with an unassigned value.

			int returnValue;

			bool result = false;

			if (!result)
			{
				Console.WriteLine("{0}", returnValue);
			}



Yes, when you declared returnValue by default it will be assigned a value of 0, its default value, but with out explicitly giving it a value the compiler will complain. This is to help prevent side-effects in your code.

Usually this happens when you use an unassigned variable inside of a block of code like an if statement or a using statement. If you want to use a variable inside of a block of code it would be best to initialize the variable explicitly.
Was This Post Helpful? 0
  • +
  • -

#7 Adkins   User is offline

  • D.I.C Addict
  • member icon

Reputation: 66
  • View blog
  • Posts: 560
  • Joined: 27-October 09

Re: Variable Initialization

Posted 04 January 2010 - 06:00 AM

@Martyr2 - are you saying that variables shouldn't be declared or initialized at the start of a function, but rather just when used? For example :

static void main(String args[])
{
    int i;
    int x = 0;

    // other random code

    i = x;
}



Would be better as:

static void main(String args[])
{
    // other random code

    int x = 0;
    int i = x;
}



If so please expand a little cause I am not following the reasoning for this. Everything within that function should be coded by you so for data protection you seal off the function. Or am I missing what was said?
Was This Post Helpful? 0
  • +
  • -

#8 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1535
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Variable Initialization

Posted 04 January 2010 - 09:39 AM

View PostAdkins, on 4 Jan, 2010 - 09:00 AM, said:

@Martyr2 - are you saying that variables shouldn't be declared or initialized at the start of a function, but rather just when used? For example :

static void main(String args[])
{
    int i;
    int x = 0;

    // other random code

    i = x;
}



Would be better as:

static void main(String args[])
{
    // other random code

    int x = 0;
    int i = x;
}



If so please expand a little cause I am not following the reasoning for this. Everything within that function should be coded by you so for data protection you seal off the function. Or am I missing what was said?


I *think* Martyr2 is saying this...

static void main(String args[])
{
	int x = 0;

	// other random code
	
	int i = x;
}



meaning to not declare a variable until you are ready to use it. This is assuming that you are using "x" in the "other random code". If not, it would go below the random code also.

That is what I got from his post.
Was This Post Helpful? 0
  • +
  • -

#9 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Variable Initialization

Posted 04 January 2010 - 01:19 PM

I would agree with eclipsed4utoo's sample code for this. You do not need to set the value of the variable twice. If you are going to use a variable it is always good practice to give it an initial value. Also, as Martyr2 pointed out, it would be a good idea to keep the lifespan of variables brief. Back in the day when I was coding in Pascal you used to have to define all variables, including index variables for loops. This was usually done at the top of the function/procedure that you were writing because that was how the person writing the textbook was taught. We are taught all sorts of bad programming practices from textbooks and now online tutorials. Remember, it is our job as programmers to write correct code that will perform as the person using the code expects. Just because you can do something in code does not mean that it is necessarily a good idea to do it. Learn to be a responsible programmer early in your career and pick up good programming skills and habits. You will thank yourself when you come back to a piece of code that you have written several months or even years ago.
Was This Post Helpful? 0
  • +
  • -

#10 kenryuakuma   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 408
  • Joined: 14-December 08

Re: Variable Initialization

Posted 04 January 2010 - 06:43 PM

:^: U are right about that 6of11, usually this is what gives me errors when it is declared and isn't initialized, and then when you use it in the for loop or do some of sort calculation and a case in point is sum = sum + 1...something as such within the if statement or the for loop.
Was This Post Helpful? 0
  • +
  • -

#11 Adkins   User is offline

  • D.I.C Addict
  • member icon

Reputation: 66
  • View blog
  • Posts: 560
  • Joined: 27-October 09

Re: Variable Initialization

Posted 05 January 2010 - 01:32 AM

I think this is something that deserves a lot more attention than the 2 sentences that it is normally allotted in most tutorials, text books, classes, lectures, and so on. Variables are always passed off as too easy a subject to even bother with any more than just a brief mention in passing. Thanks Kenryuakuma for starting this great discussion! :^:

Any other words of wisdom from the C# gurus?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1