What’s the output of the following program and why?
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
My compiler prints 0 and 1095237632. Why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In both cases you pass a bits representing floating-point values, and print them as decimal. The second case is the simple case, here the output is the same as the underlying representation of the floating-point number. (This assumes that the calling convention specified that the value of a
floatis passed the same way anintis, which is not guaranteed.)However, in the first case, when you pass a
floatto a vararg function likeprintfit is promoted to adouble. This mean that the value passed will be 64 bits, andprintfwill pick up either half of it (or perhaps garbage). In your case it has apparently picked up the 32 least significant bits, as they typically will be all zero after afloattodoublecast.Just to make it absolutely clear, the code in the question is not valid C, as it’s illegal to pass values to
printfthat does not match the format specifier.