Kshyamano
Kshyamano

Reputation: 27

Please explain This output.Value of float variable do get typecast to integer.Please explain why?

#include<stdio.h>
#define pii 3.14

void main()
{
    const float pi=3.0f;

    printf("pi= %d \n",pi);
    printf("Pi= %d",pii);
}

Output is :

pi= 0
Pi= 1374389535

I know to print float value we should use %f but why it is not typecasted in integer when we use %d.

Upvotes: 0

Views: 34

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222679

%d instructs printf to expect an int argument. It does not instruct the compiler to perform any conversion. The C standard does not define what happens when you pass the wrong argument type. A description of what happens in common implementations follows.

Passing arguments to a function is handled by the compiler. When you provide a double argument such as pii, it passes that argument to the routine being called as a double argument. When you pass a float argument such as pi, it is converted to a double due to rules for handling arguments to functions declared with ... in their parameter lists.

Processing arguments is handled by printf. It uses the format string to know what to expect. When it sees %d, it attempts to read an int. When you have passed a double and not an int, it is not able to read an int—it might read the wrong data because arguments of different types are passed in different ways, and, even if it does read the right data, it will attempt to interpret the bits of that data according to the rules for int, not double.

Good compilers can observe you are calling printf, check the format string, compare it to the arguments, and warn you if there is a mismatch. (However, a compiler cannot do this in all situations because the format string might be computed during program execution rather than a constant such as "pi= %d".) It is likely your compiler printed a warning message. However, if you compile and link the program in spite of the warning message, the program may misbehave in various ways.

Upvotes: 3

Related Questions