Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pass int value to float parameter

Tags:

c

here is my snippet of code:

float square_root(x)
float x;
{
 .......
}

int main(){
    printf("Square_root 2 = %f\n", square_root(4));
}

When I pass number 4.0 to the square_root() function, x parameter inside the function is 4.0000000 so its ok. But when I pass just 4 (like in example), x variable inside the function becomes 1.976262583365e-323#DEN

Why does that happen?

like image 805
exeq Avatar asked Oct 26 '12 15:10

exeq


2 Answers

You're using the old style of function declaration, where the argument types are listed separately. See C function syntax, parameter types declared after parameter list

As you are passing an int, it's not being converted to float by default. Your function, though, is interpreting the argument as a float, which gives undesirable results.

The modern approach is to include the argument type in the function declaration, which will allow your int argument to be automatically converted to a float.

float square_root(float x)
{
     .......
}
like image 87
Graham Borland Avatar answered Sep 23 '22 15:09

Graham Borland


There is default argument promotion with non-prototype functions and no conversion to the type of the parameter as with prototypes. So basically your int of value 4 is interpreted as a float instead of being converted to a float.

Use a prototyped definition instead:

float square_root(float x)
{
 .......
}

to have the argument at the function call converted to a float.

Also note that old-style function definitions are an obsolescent C feature and they should be avoided.

like image 22
ouah Avatar answered Sep 21 '22 15:09

ouah