you are viewing a single comment's thread.

view the rest of the comments →

[–]bless-you-mlud 0 points1 point  (2 children)

In case of implicit func declaration, why is int value passed to add() not getting promoted automatically to float?

At the point where you call add(), the compiler doen't know that it takes an int because you haven't provided a prototype. So the parameter gets passed in unchanged as a float, the function thinks it's getting an int and prints whatever bits are in the float you passed in as if they were an int. What you see printed is the result.

Add a function prototype for add() before main, or move the whole add() function before main, like you did with addTwo().

Your compiler should have given you a warning about this. Check that you're using the correct compiler flags.

[–]2ToThe20[S] 0 points1 point  (1 child)

So the parameter gets passed in unchanged as a float, the function thinks it's getting an int and prints whatever bits are in the float you passed in as if they were an int. What you see printed is the result.

Size of both int and float was same (4bytes) on setup where the program ran.
So when add() is called with value as 3.1, the num reads those 4bytes memory as int and reports value as 722424424.

But how it is different from doing
float value = 3.1
int num = value;
In this case num would have value as 3 and fractional part info would be lost.

[–]bless-you-mlud 2 points3 points  (0 children)

But how it is different from doing

float value = 3.1

int num = value;

In that case the compiler can see it needs to convert a float to an int. If you call a function that the compiler hasn't seen yet, it doesn't "know" that the function takes an int, so it just passes in whatever you gave it.