Re: printf("%d",float)
- From: Jack Klein <jackklein@xxxxxxxxxxx>
- Date: Tue, 30 Oct 2007 21:39:35 -0500
On Wed, 31 Oct 2007 01:15:33 +0000, Richard Heathfield
<rjh@xxxxxxxxxxxxxxx> wrote in comp.lang.c:
candy_init@xxxxxxxxx said:
Hi all,
I just came across the following program:
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
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?
You are wrong in thinking that %d is the appropriate format specifier for a
float, and you are wrong in thinking that you can meaningfully cast the
address of a float into the address of an int.
You were right in the first pronouncement, not necessarily so in the
second. The result of casting a pointer to an object or incomplete to
a pointer to any other object or incomplete type, is undefined if the
pointer is not suitably aligned for the second type, but well defined
if there is no alignment error. Of course, dereferencing that pointer
is completely undefined.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
.
- Follow-Ups:
- Re: printf("%d",float)
- From: Richard Heathfield
- Re: printf("%d",float)
- References:
- printf("%d",float)
- From: candy_init
- Re: printf("%d",float)
- From: Richard Heathfield
- printf("%d",float)
- Prev by Date: Re: printf("%d",float)
- Next by Date: Re: Macro that expand differently depending on the function calling it.
- Previous by thread: Re: printf("%d",float)
- Next by thread: Re: printf("%d",float)
- Index(es):
Relevant Pages
|