Output EOF using %f

159 views Asked by At
#include<stdio.h>
int main()
{
    printf("%d",EOF);
}

generates -1 which is totally fine, but

#include<stdio.h>
int main()
{
    printf("%f",EOF);
}

produces 0.000 . How can someone explain this when the expected output is -1.000?

2

There are 2 answers

1
Natasha Dutta On BEST ANSWER

Using a wrong format specifier for any particular argument in printf() invokes undefined behaviour.

EOF is of type int. You can only use %d for an int type variable.

FWIW, if you want a floating point representation of an int, you have to cast the variable (but I personally recommend to avoid this)

printf("%f",(float)EOF);
2
haccks On

EOF is of int (signed) type. You should not use wrong format specifier to print int, otherwise it will invoke undefined behavior.