5

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?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
exeq
  • 379
  • 1
  • 5
  • 15

2 Answers2

17

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)
{
     .......
}
Community
  • 1
  • 1
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
6

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.

ouah
  • 142,963
  • 15
  • 272
  • 331