Home > Enterprise >  Division of two numbers in printf return garbage value in c
Division of two numbers in printf return garbage value in c

Time:03-27

In printf("%d", (float) 9/ (float) 5); what will be the output?

Note: In printf function the format specifier is %d

It seems that output would be 0 just like the below code return answer 0.

float a = 9/5;
printf("%d",a);

But not at all. The correct output is -1073741824 as a Garbage Value And that's the question. Why?

We can do the explicit typecasting to convert integer data type to float data type.

But why typecasting is not working in this printf("%d", (float) 9/ (float) 5); code?

I know this is a stupid question but I want to know this stupidity.

CodePudding user response:

printf() has no way to know what type you are passing in other than the "%d" format specifier you've given it. When it sees "%d" it will use va_arg() to extract an integer from the arguments it received. There is no integer there, so anything could happen. Floating point values are often passed in different registers than integers, so it's not like you're just interpreting a float as an int, you're actually loading an int from some unknown place.

CodePudding user response:

The value of (float)9 / (float)5 (or more simply 9.0f / 5.0f) is 1.8f. Whereas the value of 9/5 is 1, and when assigned to a float implicitly cast to 1.0f (equivelent to (float)(9/5)).

In both cases interpreting either value using the %d format specifier has undefined behaviour but the result differing is hardly surprising since the input differs. That said even if the values were the same, that too should not be surprising - that is the thing with undefined behaviour - all bets are off.

  • Related