Re: printf("%d",float)



candy_init@xxxxxxxxx wrote:

Hi all,
I just came across the following program:

#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);

printf expects and treats the corresponding argument as a signed int,
while you've passed it a float value.

printf("%d\n", *(int *)&a);

Same as above and an additional problem:

Pointers values of different types need not be compatible in C, except
that a conversion of any pointer to void * and back again shall be
okay.

return 0;
}

The program prints 0 and 1095237362. However, in my opinion it should
print 12 at both the places. Can anybody tell me where I am wrong?

Yes. You've written an incorrect program, so incorrect results are to be
expected.

Read:

<http://www.c-faq.com/>

.



Relevant Pages

  • Re: printf("%d",float)
    ... The program prints 0 and 1095237362. ... float, and you are wrong in thinking that you can meaningfully cast the ... address of a float into the address of an int. ... The result of casting a pointer to an object or incomplete to ...
    (comp.lang.c)
  • Re: printf("%d",float)
    ... The program prints 0 and 1095237362. ... float, and you are wrong in thinking that you can meaningfully cast the ... address of a float into the address of an int. ... The result of casting a pointer to an object or incomplete to ...
    (comp.lang.c)
  • Re: printf("%d",float)
    ... int main ... float a = 12.5; ... The program prints 0 and 1095237362. ... printf("if the args interpret as int, you get %d\n", i); ...
    (comp.lang.c)
  • Re: printf("%d",float)
    ... The program prints 0 and 1095237362. ... float, and you are wrong in thinking that you can meaningfully cast the ... address of a float into the address of an int. ... Google users: ...
    (comp.lang.c)
  • Re: Abnormal program termination
    ... foo.c:4: warning: function declaration isn't a prototype ... Your version is legal under C90 rules, but int mainis more explicit ... float ave(), average; ...
    (comp.lang.c)