vlsidesign wrote On 11/08/07 15:54,:
Newbie question: 0 converted to 0.0 for float variable?
If I have the following code,
float myTotal;
myTotal = 0;
will C automatically add a decimal point and at least one zero to the
right of the decimal place? I am expecting that 0 will become at least
0.0 or maybe something with more zeros.
Strictly speaking, the statement involves a float
variable and an int value. When you assign a value of
one type to a variable of a different type, the value
is converted to the type of the variable (if possible)
as part of the process. So the statement says
- obtain an int with the value zero
- convert it to the equivalent float value
- store that float value in myTotal
In practice, most compilers will recognize that 0
is not just an int but an int whose value does not change,
and therefore they will know that the conversion from int
to float will always produce the same result. So they'll
take a shortcut and generate code to do
- obtain a float with the value zero
- store that float value in myTotal
Note that I'm being very careful to talk about types
(int, float) and values (zero), not about how the values
are represented in C source. The description above does
not talk about adding decimal points or adding zero digits
to something in your source code; it talks about what the
computer does with the values and variables that your
source code defines. You need to know what the various
code constructs mean -- 0 and 0.0 and .0f and 0L and 0u
are all zeroes, but all different -- but you should think
of the program as working with the values, not with the
source code that produced them. You'll be happier that
way, I promise.
--
Er*********@sun.com