1

I just started learning C and I'm having trouble understanding why the following code even works at all:

void convertMyNumber (float myValue) {
    int myNewValue = floor(myValue * 100);
    printf("%d", myNewValue);
}

Looking at the documentation for math.h, it is stated that the floor() function takes a double as an argument, and also returns a double. So far so great, I just ran the above code and typed in 576.73 as the value for the myValue variable. Surprisingly (to me), it printed out exactly 57673 on the screen, and I'm finding it difficult to understand how it is possible that it was able to attribute the returning value of the floor function (a double) to int myNewValue.

3 Answers3

2

This line int myNewValue = floor(myValue * 100); contains no less than 3 implicit conversions.

  • In myValue * 100, the integer constant 100 is of type int. An implicit conversion known as "the usual arithmetic conversions" convert the int operand to float. The multiplication is carried out on float and the resulting type is float. See Implicit type promotion rules.

  • The float result from the previous calculation is converted to the type of the function's operand. Function parameters are implicitly converted "as if by assignment", converting the passed argument to the type of the parameter, in this case double.

  • The result of double is converted by assignment to the type of the left operand int. If the double contains a value which can be represented by an int, this conversion is well-defined.

So this is why it works, but relying on implicit conversions is often not a good idea, since the potential for accidental bugs is great.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

In an assignment, value of the right-hand side operand is implicitly converted into the type of left-hand side operand. That's how floor(576.73 * 100) = 57673.0 became 57673. C does this by taking the double value and ignoring (truncating) its fractional part.

k-var
  • 15
  • 8
0

As mentioned in the comment what you are looking at is an implicit, or eqyivalently, automatic type conversion that is done by the compiler. The example below shows how you could perform the conversion explicitly, also called "type casting".

#include <stdio.h>
#include <math.h>

void f_to_i(float f);

int main(int argc, char *argv)
{
  float fl = 576.73;
  f_to_i(fl);
}

void f_to_i(float f)
{
  int i;
  // Implicit Conversion
  i = floor(f * 100);
  printf("%d\n", i);
  i = 0;
  // Explicit Conversion
  i = (int)floor(f * 100);
  printf("%d\n", i);
}
Sigve Karolius
  • 1,356
  • 10
  • 26