Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the returning from a double function becomes int?

Tags:

c

int

double

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?

like image 256
Akr Avatar asked Feb 15 '26 23:02

Akr


1 Answers

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.

like image 69
M.M Avatar answered Feb 17 '26 14:02

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!