1
1230987za
Hi,
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;
}
I had imagined the output is
ff=42.7
dd=42.7
dd1=43.7
But what I see is
ff=42.700001
dd=-1610612736
dd1=1078286745
Then I coded this test:
int main(){
int ii = 7;
char cc = (char) ii;
printf("cc=%c\n", cc);
cc = 7;
printf("cc=%i\n", cc);
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;
}
I see this result:
cc=
cc=7
u.c=
u.l=7
u.c=
u.l=7
This is as I expected, but since I was so off by the first test,
could you confirm there is no compiler/OS dependent thing in the 2nd
test -- it should always output that result?
And how about the 1st test?
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;
}
I had imagined the output is
ff=42.7
dd=42.7
dd1=43.7
But what I see is
ff=42.700001
dd=-1610612736
dd1=1078286745
Then I coded this test:
int main(){
int ii = 7;
char cc = (char) ii;
printf("cc=%c\n", cc);
cc = 7;
printf("cc=%i\n", cc);
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;
}
I see this result:
cc=
cc=7
u.c=
u.l=7
u.c=
u.l=7
This is as I expected, but since I was so off by the first test,
could you confirm there is no compiler/OS dependent thing in the 2nd
test -- it should always output that result?
And how about the 1st test?