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);

This line is wrong because printf() expects an int but a is a float. Note that because this is undefined behaviour (UB), this may cause a crash on some C compilers - and even worse behaviour on others.

<OT>
To think about one reason this may crash on a machine with a stack, if sizeof(float) != sizeof(int) then printf() will remove the wrong number of bytes from the call stack, leaving the stack in an inconsistent state after the call to printf().

A C compiler doesn't /need/ a reason like this to fail, however; if the behaviour is undefined, it can do anything it likes for no reason at all.
</OT>

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

I'm curious. Why did you write this instead of the correct (and simpler):

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

This converts the float value to an int value.

Your version takes the address of a to produce a 'float *', converts that pointer to an 'int *', and dereferences that pointer. Converting a float pointer to an int pointer isn't very meaningful.

--
Philip Potter pgp <at> doc.ic.ac.uk
.



Relevant Pages