Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we must initialize a variable before using it? [duplicate]

Tags:

c

Possible Duplicate:
What happens to a declared, uninitialized variable in C? Does it have a value?

Now I'm reading Teach Yourself C in 21 Days. In chapter 3, there is a note like this:

DON'T use a variable that hasn't been initialized. Results can be unpredictable.

Please explain to me why this is the case. The book provide no further clarification about it.

like image 429
user774411 Avatar asked Oct 16 '11 20:10

user774411


People also ask

Why do we need to initialize a variable?

To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable. Most of the times, Java wants you to initialize the variable.

Which variables need to initialize before using it?

Local Variables. Local variables must be initialized before use, as they don't have a default value and the compiler won't let us use an uninitialized value.


1 Answers

When a variable is declared, it will point to a piece of memory.

Accessing the value of the variable will give you the contents of that piece of memory.

However until the variable is initialised, that piece of memory could contain anything. This is why using it is unpredictable.

Other languages may assist you in this area by initialising variables automatically when you assign them, but as a C programmer you are working with a fairly low-level language that makes no assumptions about what you want to do with your program. You as the programmer must explicitly tell the program to do everything.

This means initialising variables, but it also means a lot more besides. For example, in C you need to be very careful that you de-allocate any resources that you allocate once you're finished with them. Other languages will automatically clean up after you when the program finished; but in C if you forget, you'll just end up with memory leaks.

C will let you get do a lot of things that would be difficult or impossible in other languages. But this power also means that you have to take responsibility for the housekeeping tasks that you take for granted in those other languages.

like image 170
Spudley Avatar answered Oct 29 '22 16:10

Spudley