Initializing variables

How important is it to initialize a variable?Is it a good habit to initialize every variable to 0?
You should initialize variables, it is good programming practice because a uninitialized variable can contain anything and you may later find yourself trying to track down why you have a weird number in your calculation. it can be much easier to find if you initialize it.

Also when using pointers, an uninitialized pointer can actually be dangerous. As you may inadvertently change data that does not belong to your program. As it's uninitialized It can point to any block of memory.

Is it a good habit to initialize every variable to 0?


I would suggest only creating the variables when you are going to use them.
If you need to create a variable earlier 0 is accepted, unless you are going to use the variable as a dividing factor as dividing by 0 will cause a hang followed by a crash in most cases.
Last edited on
> How important is it to initialize a variable?

Postpone definition of a variable to the point of its first use - till when you know what to initialize it with. Strive to keep the scope of a variable as small as possible (the life-time of a variable as short as possible).


> Is it a good habit to initialize every variable to 0?

No. Prefer 'real' initialisation over 'fake' initialisation.
un-initialized variable make program non-deterministic because each time you run programme it behave differently
Topic archived. No new replies allowed.