Monday, May 16, 2011

Do variables need to be initialized?

No. All variables should be given a value before they are used, and a good compiler will help you find variables
that are used before they are set to a value. Variables need not be initialized, however. Variables defined
outside a function or defined inside a function with the static keyword (those defined in the data segment
discussed in the preceding Question) are already initialized to 0 for you if you do not explicitly initialize them. Automatic variables are variables defined inside a function or block of code without the static keyword.
These variables have undefined values if you don’t explicitly initialize them. If you don’t initialize an
automatic variable, you must make sure you assign to it before using the value.
Space on the heap allocated by calling malloc() contains undefined data as well and must be set to a known
value before being used. Space allocated by calling calloc() is set to 0 for you when it is allocated.