0

Below program outputs different values for a/100 where a is int.

void main()
{
    int a = -150;
    float f;
    f = a/100;
    printf(" %f,%f ",f,a/100);
}

Output: -1.000000,0.000000

Here second %f value comes up to 0.000000, but how is it possible, it should be -1.000000 or -1.500000.

0

1 Answer 1

4

There is no inconsistency:

 f = a/100;

performs integer division stored into a float: result 1.0

then

 printf(" %f ",a/100);

prints an integer (1), but with float format: undefined behaviour.

this works without surprises:

void main()
{
    int a = -150;
    float f;
    f = a/100.0;
    printf(" %f,%f ",f,a/100.0);
}

printf is a variable arguments function (prototype: void printf(const char *,...)), which has no other choice than to "believe" the format that you pass.

If you tell printf that second argument is a float, then it will read the argument bytestream as a float, and if the data doesn't match a float structure, well, it won't work properly.

EDIT: compiler makers know that this is a common mistake, so they have added a special check for the printf-like functions: if you compile your file with gcc using -Wall or -Wformat options you'll get the following explicit message:

foo.c:8:1: warning: format '%f' expects argument of type 'double', but argument 3 has type 'int' [-Wformat=]
 printf(" %f,%f ",f,150/100);

(same goes if the number of %-like format arguments and the number of arguments do not match).

Sign up to request clarification or add additional context in comments.

2 Comments

So, I should not use %f with an underlying integer unless I cast? ( Say, I do not want to use 100.0 as denominator). I knew it would print correctly when the modifications you had mentioned are done. MY POINT IS WHY DOES IT NOT INHERENTLY typecast int to float when %f format specifier is used.
@iharob: what was I thinking :) edited. no need for further complexity...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.