-
6Please put everything directly in your question as text, not images and not links to offiste images. – Stephen Newell May 24 '21 at 16:01
-
2[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/995714) – phuclv May 24 '21 at 16:11
2 Answers
The argument passing conventions of many architectures/OSes/ABIs nowadays are register-based, at least for the first few arguments. Integer and floating point on most architectures use entirely separate registers. When you tell it to print %f
, it looks in the floating point registers, but the argument, being an int
, was passed in an integer register; they don't see each other at all, so you won't even get "half garbage" (where some of it is integer bits interpreted as floating point), it's "full garbage" (where you see whatever happened to be left behind in that register from the last time it was used).
In your case it was 0.0
, but it might be something different the next run, or built by a different compiler, or affected by the phase of the moon, etc. It's undefined behavior, so C/C++ specs don't bother to get any more detailed than that.

- 143,180
- 12
- 188
- 271
-
That is actually a very good answer - it goes beyond undefined behavior and explains the observed results. – SergeyA May 24 '21 at 17:46
First of all, your assumptions are generally speaking incorrect. Both integers and floats are promoted when passed as arguments to variadic functions, so assuming most common architectures nowadays, they would both become 8 bytes in size.
Having said that, this code triggers undefined behavior, as you are trying to treat binary representation of float number as integer. Undefined behavior can have seemingly random observed effects, and in your case, it is 0 being printed - but from language standpoint, it is completely random.

- 61,605
- 5
- 78
- 137
-
Where "random" here means "arbitrary, coincidental, unreliable, and happenstance", rather than "here's a clever useful way to get random numbers". – Eljay May 24 '21 at 17:25