Hi, I am a long time matlab user, now I am learning C but can´t understand
the following:
1)If I define a variable, without giveing a value to it, the compiler
gives any value to it.
Looks like Joona missed that first one [it is not likely he does not know
the answer ;-) ]
There are different "storage classes" for variables in C, and the storage
class determines whether or not a variable is initialized with a default
value (if you don't use an initializer).
Variables with "static" storage, that is, having a fixed location in memory
(for example: file scope [ a.k.a. "global", or "external"] data, and data
declared "static" at block scope) get zero-initialized. "Zero" is
appropriate for the object's type (as opposed to necessarily meaning all
0-bits.)
Automatic storage (non-static data defined at block scope, otherwise known
as garden-variety local data) and some dynamic storage (such as that
obtained from malloc()) is not initialized; it contains garbage, or
whatever was there before. In the case of floating-point data and pointers,
you really want to make sure that the very first thing you do with such
uninitialized storage is assign a value to it. Doing so as a bona-fide
initialization at the point of the object's definition is best (for
pointers, it is generally considered safer to set them to NULL rather than
leaving them containing garbage, but this is a Religious Issue). A plain
assignment later on is also ok, so long as you don't forget to do it....
because reading an uninitialized floating point or pointer value invokes
undefined behavior.
-leor