0

I ran some code in C, and I ran into an interesting occurance when printing integers in float place. This is the code: `

#include <stdio.h>

int main()
{
    printf("%f\n",5);
    printf("%f\n",5.5);
    printf("%f",5);

    return 0;
}

The output is:0.000000 5.500000 5.500000`

My question is why it repeats the value? Specifically how it works on low level

I thought it might be connected to the stack.

Lior G
  • 1
  • 4
    Undefined behavior. The "low level" explanation will depend on the specific platform, compiler, optimization options, surrounding code, etc, etc. – Nate Eldredge Nov 18 '22 at 06:13
  • You will have to rework your post with the help of https://stackoverflow.com/editing-help Otherwise it looks like the shown code cannot possibly create the output you show. – Yunnosch Nov 18 '22 at 06:15
  • 1
    But on some platforms, floating-point arguments are passed in a separate type of register than integer arguments. So `printf("%f", 5)` may ignore the 5 completely and print whatever happens to be in the relevant floating-point register. Maybe it's 0 the first time. And maybe the third time, your value `5.5` is still in that register because nothing happened to overwrite it yet. I hope it goes without saying that there is no guarantee that this or anything like it will always happen. – Nate Eldredge Nov 18 '22 at 06:15
  • Lesson: Do not ignore the standard. – Sourav Ghosh Nov 18 '22 at 06:16
  • 2
    Enable warnings and treat warnings as errors. You would have gotten something like: `error: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Werror=format=]` for the 1st and 2rd call to `printf`. – Cheatah Nov 18 '22 at 06:17

0 Answers0