Akr
Akr

Reputation: 199

Why the returning from a double function becomes int?

I have a double function like this:

double f(){
     double value=0.1234;
     return value;
}

In another function I received the value and printed it.

printf("%f",f());

I would like to see the value 0.1234 was printed, but instead 0 was printed. If I cast the type like this:

printf("%f",(double)f());

a very strange value like -147923499.34 would be printed.

After some checking (print sizeof) I found that the returned value from f() was 4 bytes, while the double type should be 8 bytes.

So, what is the root reason of this? How can I return the correct double value from the function?

Upvotes: 2

Views: 3758

Answers (1)

M.M
M.M

Reputation: 141554

It sounds like you called f() without a prototype in scope. In C89, the compiler reacts to this by assuming f returns int. If the implementation of f does not actually return int then the behaviour is undefined.

In C++, and in C since C99, there must be a warning at least for this code. Check your compiler output and I would recommend that you pay attention to any warning messages, and if there were none, turn up the warning level.

To fix the code, write a prototype:

double f(void);

before calling the function. It's normal to place the prototype in a header file which is included by both the code calling the function, and the code implementing the function. Then the compiler will detect a mismatch between call and implementation.

Upvotes: 9

Related Questions