writes:
> I am totally confused now about C type conversion.
>
> I know that C does some implicit type conversion like integer
> promotion and float to double. I imagine that such conversion must
> keep the value through, meaning that the converted value equals to
> their originals.
>
> But the following code blew me away:
>
> int main(){
> float ff = 42.7;
> double dd = ff;
> double dd1 = ff + 1.0;
> printf("ff=%f\ndd=%d\ndd1=%d\n", ff, dd, dd1);
>
> return 0;
> }
You need '#include <stdio.h>' at the top of the file. Calling printf
(or any other variadic function) with no prototype in scope invokes
undefined behavior. You're likely to get away with it, and it's
probably not the actual cause of your problem, but you should correct
it anyway.
Your real problem is that your format string is incorrect. The "%d"
format expects an argument of type int, not double (the 'd' stands for
"decimal"). And "%f" expects an argument of type double, but a float
argument is promoted to double (because printf is a variadic
function).
Try this:
#include <stdio.h>
int main(void)
{
float ff = 42.7;
double dd = ff;
double dd1 = ff + 1.0;
printf("ff=%f\ndd=%f\ndd1=%f\n", ff, dd, dd1);
return 0;
}
[...]
> Then I coded this test:
>
> int main(){
> int ii = 7;
> char cc = (char) ii;
The cast is unnecessary; the value will be implicitly converted
without it.
> printf("cc=%c\n", cc);
>
> cc = 7;
> printf("cc=%i\n", cc);
"%i" is equivalent to "%d", so this is ok. Most C programmers use
"%d" rather than "%i"; I'm not sure why "%i" is supported, but it is.
> union {
> char c;
> int i;
> long l;
> } u;
>
> u.i = 7;
> printf("u.c=%c\n", u.c);
> printf("u.l=%li\n", u.l);
>
> u.c = (char) u.i;
> printf("u.c=%c\n", u.c);
> printf("u.l=%li\n", u.l);
>
>
> return 0;
> }
You're doing some dangerous stuff here. Storing a value in one member
of a union and then reading a different member invokes undefined
behavior. (There are exceptions for character types, but it's still
tricky.) In practice, after you've stored the value 7 in u.i, reading
u.c should give you the first byte of the int. The number of bytes in
an int, and the order in which they're stored, varies from one
implementation to another. Most likely you'll get either a null
character or an ASCII BEL character, but it's not guaranteed to be
either.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"