What is variable initialization and why is it important?

Recommended Answers

All 3 Replies

When you declare a variable, the compiler gets a "box" and labels it with the name of your variable.
The kind of box taken, depends on the type of your variable. The "box" will be bigger if the type is float, than in case of an int.
Let us say you have as declaration: int myInt = 42;
So the compiler takes a "box" for an int and labels it with myInt. Now the problem is(because this "box" is taken out of free memory, that the box already has a value in it. So, initialisation is very important. Hope this little story helps a bit.

Member Avatar for MonsieurPointer

Here is another example why initialization is important:

int *pSomeInt;
...
if (pSomeInt != NULL)
{
free(pSomeInt);
}

pSomeInt is not initialized to NULL, therefore it is highly likely the compiler will assign some junk address. Since the if-statement could fail, the program could crash.

Motto: Always initialize your pointers to NULL!

Actually the standard says that use of any automatic variable before it has been either initialised or assigned is undefined behaviour, which as we all know is bad.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.