Initializing Variables (C++ programming)?

Pages: 12
I'm struggling to understand why we initialize variables in C++ though I have some idea. Could anyone explain this to me.

I have the books and have read the standard answers on the web about how 'Otherwise the variables will contain garbage and cause errors', or 'Uninitialized variables can cause unpredictable results'.

The way I'm seeing it is this. When, for example, you are using VBA you can declare a variable, eg: Dim VariableOne as String, you can safely run the VBA subroutine without giving VariableOne a value. I know this isn't the same kind of programming as C++. Why then do we have to initialize variables in C++. Why not just declare the variable say: int VariableOne; and use it later on in our program? I may want to apply a value typed into a GUI to this variable, otherwise I'm not using it until i'm using it (you know what I mean).


The only reason I can come up with is that an uninitialized variable 'Won't Compile' ?? Is that the reason? Meaning that it can't be safely converted to machine language when compiled. If it's not being used until I apply an inputted value to it then why do anything with it until then?

I hope this is clear. Please read my abstract VBA example again if not. I just can't understand why I would bother to initialize a variable or why an uninitialized variable would even affect a program until I'm using it.

Thanks so much.
This concept is driving me nutts.

Thanks
dominover
When you first start programming in C++ and you learn that one should initialize variables, it can seem like too much work. But trust me, when you work on a program that several other people also work on, you will find that uninitialized data will bite you, and these problems are sometimes hard to find!

One good reason is when you have to test a variable to see if it has been set to a specific value. If you don't initialized it to a known value, you won't necessarily know if the variable you test has a valid value.


You don't have to initialize variables, just don't use their values before you assigned anything meanigful to them.
The point of declaration and assignment should be at most a few lines apart so there can be no doubt that the code is correct. When that is not possible, initialize it to a default value, even if you think it is never used. You don't want to work with "probably and maybe" in programming.

Things are different for class instances. For them, the default constructor is called, so for example, a std::string is initialized to an empty string.
Last edited on
Thanks for the replies kooth and Athar. I see some sense in what you have both said.
I'm happy to initialize, but I also want to know why I would bother.

The reason is:

Ultimately, I create a variable to use somewhere in the program. Either in a main module or in a class object. Eventually I will use one of these variables several times and the value of that variable will change depending on what data I enter into my application user interface. What I'm saying is, the first time I have any use for that variable is when I'm assigning a value to it. Then why would I bother to assign a value to it before I actually use it? How will this unitialized variable bite me if I'm not using it. Do you see what I mean. I gave the VBA example as it explains this perfectly. If I'm not going to use a variable until a particular point in time (thats when I allocate a value to it from something I've entered into a GUI) then why add a known value to it before hand. What's the point.


There must be some theory behind this? This same idea goes for member variables as well. I'll ultimately use them so why allocate them a value until I actually use them. How will I have problems if I'm not using them.

Sorry for my repetition, I just want to be clear.

Thanks again.
Dominover
I think there's some confusion about what initialization means here.

If you write int a; you get a valid, probably 4 bytes wide block of memory. Initialization is in this case just the first assignment a=something;, before that you will have whatever garbage value originally was at that point. An example to illustrate:

Imagine a 6 byte block of memory like this:


| 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00


Now, you need the character '0' somewhere, this character variable ends up in our memory block:


| 0x00 | 0x30 | 0x00 | 0x00 | 0x00 | 0x00


Now that character goes out of scope, but now you want an integer. You don't assign a value to it though, so coincidentally that 4 byte int ends up in our memory block as well:


| 0x00 | 0x30 | 0x00 | 0x00 | 0x00 | 0x00


So now our uninitialized integer has a value of 3 145 728, which isn't necessarily what you'd expect (and surely enough isn't a useful value to work with). That's all there is to it, really.
Last edited on
The way I'm seeing it is this. When, for example, you are using VBA you can declare a variable, eg: Dim VariableOne as String, you can safely run the VBA subroutine without giving VariableOne a value. I know this isn't the same kind of programming as C++.
When you don't specify a value (initialize it) VB initializes it for you, in your example your string would be nothing. C++ does this for objects, it will not do this for primitives. So to answer your question VBA does it for you, so it is happening.

What I'm saying is, the first time I have any use for that variable is when I'm assigning a value to it.
Then why not declare and initialize that variable (if possible) at that time? It makes the code easier to follow. I cant count how many times I've had to scroll up and down pages of code to look back at variables to see what their type/value was/is because of this.

When you write code, you are giving the computer an instruction set. It does not assume things for you, if you do something like:

1
2
3
int jumper;
//...
jumper+=2; //What does jump = jumper + 2 evaluate to? 


As far as classes go, you should always initialize members to some known default value, if you wrote your own custom string class call it StringClass. Users would probably want to be able to do something like this...

 
StringClass temp; //temp = ""    Because in your default constructor you implement it this way 


You provide defaults as the VBA compiler does for you, just know this, just because it is not required to initialize variables explicitly in VBA does not mean the compiler is not doing it for you. In other words, you need to initialize your variables, the same as other languages that do it for you.
Thanks again for the replies.. I'm getting there. Not at all criticizing your answers, I just need to intuitively understand this. Hanst99, good explanation, it's definitively clarified something for me. The unpredictable nature of an unitialized variable is surely solved when we come to use a variable and overwrite the garbage currently assigned to this unitialized variable.


If we create a program and therefore variables in that program, we create these variables for a reason. At some stage we will use these variables. Maybe we'll allocate a result of a function (a function which was engaged somewhere in main)? If this is the case, then why initialize the value before hand. If we are going to assign a value to a variable sometime later in the program (in some ad-hoc fashion), then that value will override any initial garbage value that variable is holding? (do I have this wrong?).

The only reason I can think of why would be that if we declare an int for example: int VaribleA; and when we first run a program a garbage value is assigned to 'VariableA', it may not be compatible with the type of variable (in this case int).
OR
The amount of memory that variable is holding is unpredictable, meaning that we may be using more memory than we initially expected to simply because we did not initialize our variable. I want to intuitively understand this.

Thanks
There is no difference between assignment and initialization, if you assign something later you are just delaying the initialization. An uninitialized value is never useful.
There is no difference between assignment and initialization, if you assign something later you are just delaying the initialization. An uninitialized value is never useful.

Why do we need it to be useful before we use it? Thats the ultimate question.
dominover wrote:
Why do we need it to be useful before we use it?

Why create it before you need it?
Why create it before you need it?


Because we're talking about programming. I've given several examples already.
If I have a GUI and I enter a value and want the program to assign that value to a variable which will be later on utilized in a function / member function / sum etc.... I will just need that variable then. So I declare the variable in the program so when I need it, it's there.

I won't suddenly go back to the source code when I enter a value into a GUI and add the variable because I need it then only. I create the variable before hand so I can use it later on.

Why would I assign a value to it before I need to assign a value to it. The initialization process happens before this but their's not theoretical backing as to why??

Does it have to do with the stack?
Maybe it has to do with the size of the variable once a value has been assigned to it. Is that the unpredictable part? Unpredictable if we can't determine that early (by initializing the variable).

I'm starting to think there is no explanation for this. Programmers simply take this for face value because that's how they're taught to think. 'Just initialize your variables but don't ask why' because there's no theoretical backing as to why.

I know what will possible happen if I don't but why does that happen? That's the clearest I can be.

Thanks so much.
Dominover






I won't suddenly go back to the source code when I enter a value into a GUI and add the variable because I need it then only. I create the variable before hand so I can use it later on.


That's a nonexample. That doesn't happen, and isn't related to the question of initialization in any way.

It seems to me as if you're still completely unclear as to what you are talking about. First of all - you don't HAVE variables you don't need. If you do anyways, that's a sign of bad code. The example you gave doesn't make sense - if you know you have a textfield you read data from, you also know WHEN you will need that data. Not 'when' as in time, but 'when' as in where in your program. Initialization is the initial assignment of a value to a variable. A variable that does not contain useful data is not useful. Now the only thing I can imagine your problem to be is the position of the initialization, that is, immediately at declaration or the first time you're using it. Again, this making any significant difference is an indicator for bad design. There is no conceptual difference between

1
2
int a;
a=5;


and

 
int a = 5;


although there would be a difference if a was of an object type (for which declaration and initialization always coincide).

So quite frankly, where is the problem? It shouldn't be hard to understand that

1
2
int a;
do_something_with(a);


is bad.
-Wuninitialized: Warn if an automatic variable is used without first being initialized.
These warnings are made optional because GCC is not smart enough to see all the reasons why the code might be correct despite appearing to have an error.

-Werror : Make all warnings into hard errors. Source code which triggers warnings will be rejected.


If you can span 10 LOC without using your variable, then declare your variable 10 LOC further.
What I should have asked is 'why do I initialize a variable before I assign to a variable'?

I'm thinking it has something to do with the compiler. That's the only explanation I can really put to this. A constructor does this for example.
A constructor needs to initialize the members in order to preserve some invariants.

The only reason I can think of why would be that if we declare an int for example: int VaribleA; and when we first run a program a garbage value is assigned to 'VariableA', it may not be compatible with the type of variable (in this case int).
Nope. An int will always hold an integer. That's the point of the type.

The amount of memory that variable is holding is unpredictable, meaning that we may be using more memory than we initially expected to simply because we did not initialize our variable. I want to intuitively understand this.
Nope, sizeof is computed at compiled time. It's a type property.

why do I initialize a variable before I assign to a variable?
assignment (for the first time) is initialization.

1
2
int n = 42; //this assignment has no purpose
cin >> n; //as we are overriding the value here 


I'm thinking it has something to do with the compiler
¿Could you be a little less specific?
In your wording, initializing (construction) is a special case of assignment; it occurs when the variable is made instead of later.
I'm certain now that nobody knows the answer to this. It's just one of these things we take for granted. It's like saying, " You should always put fuel in the car" without knowing that the car actually runs on fuel. We just do it because that's what the book says, that's what we're told and that's what the neighbors do. I'm just trying to highlight a point here, not trying to play word games.

I should be able to create a variable with no value assigned to it. This variable will only be used in once situation. That is if I enter a value into a GUI or press a button ect. Otherwise the variable remains empty.

A variable is like a cup. Declaring a cup allocates a space for an int or string etc. It's just allocated space that's it until I need that space to store something in it. Why I need to fill the cup with something before want to fill this cup?? Why can't I just leave it empty until it is needed to store a variable (received from user input, should that user input be required at some stage.

'''''' So what if it's filled with garbage before I initialize it or assign a value to it, I'm going to overwrite that garbage when I need the variable anyway ''''''''''' AND,,,, if i don't need the variable when I run the program this time,, it will just contain garbage. How does this cause problems??.

If this does not make sense.. Just think about what I have said in the context of a constructor and it's role. Why does it have to initialize member variables before you assign something to it. No,,, in this case Initializing an Assigning are not the same thing.








I'm certain now that nobody knows the answer to this. It's just one of these things we take for granted.

This question has already been answered in this thread.

Athar wrote:
You don't have to initialize variables, just don't use their values before you assigned anything meanigful to them.


kooth wrote:
...you learn that one should initialize variables, it can seem like too much work. But trust me, when you work on a program that several other people also work on, you will find that uninitialized data will bite you, and these problems are sometimes hard to find!


hanst99 wrote:
So quite frankly, where is the problem? It shouldn't be hard to understand that

1
2
int a;
do_something_with(a);


is bad.

In short, you don't have to initialize variables, but it is good practice to do so.

I should be able to create a variable with no value assigned to it. This variable will only be used in once situation. That is if I enter a value into a GUI or press a button ect. Otherwise the variable remains empty.

You can do that. It doesn't mean that you should.

Why I need to fill the cup with something before want to fill this cup??

You can do that. It doesn't mean that you should.

So what if it's filled with garbage before I initialize it or assign a value to it, I'm going to overwrite that garbage when I need the variable anyway

It will cause problems if it's accessed before you assign a value to it.

This won't cause problems:

1
2
3
4
int x;
doStuff();
maybeDoSomeOtherStuff();
x = 5;


This will cause problems:

1
2
int x;
doStuffWith(x);


In small projects, where you're the only developer then you can probably get away with skipping initialization and only assigning to variables as necessary. However, on larger projects, other people will use (and misunderstand) your code and it will save lots of headaches if you initialize all your variables, as kooth aluded to. Again, you don't have to initialize variables but it is good practice to do so.
Last edited on
dominover, are you declaring all your variables as member variables or globals? If you need a variable only in one function you create that variable in that function when you need it! Sometimes you don't have a value to give the variable on the same line as the variable is defined but at least it will be initialized very soon in the lines to follow.
> A variable is like a cup. Declaring a cup allocates a space for an int or string etc.
> Why I need to fill the cup with something before want to fill this cup??
> Why can't I just leave it empty until it is needed to store a variable
> received from user input, should that user input be required at some stage.

Defining a variable always implies initializing it - if you don't initialize it explicitly, it is default initialized. For some types (like int), default initialization is trivial initialization - nothing needs to be done. For others (like std::string), default initialization is not trivial - the default constructor comes into play. For example, for a std::string, the default constructor initializes it to an empty string.

The problem with code of this kind:
1
2
3
4
5
6
7
8
int number ; // initialization is trivial; number may contain any value at all

// ....

// sometime much later
std::cout << "please enter a number: " ;
std::cin >> number ; // assign a meaningful value (entered by the user) to number
// use number 

is that it is prone to errors - because of a slip, number may be used without having been assigned a meaningful value. For instance, in the above example, if when prompted with "please enter a number: ", the user enters xyz, the attempted input fails, and nothing will get assigned to number.


Also, where possible, postpone definition of a variable till the time time you know how to initialize it. If the initialization is trivial, it increases the clarity of code. If the initialization is not trivial, it could also make the code more efficient.
See: http://www.civilnet.cn/book/kernel/Effective%20C++%20(Third%20Edition)/ch05lev1sec1.html




Pages: 12