1

I use the Cosmic C Compiler for STM8 micro controllers and use float variables. For the currently used platform the compiler does not provide double types. Anyway, when one uses doubles they are treated as floats.

I wonder whether it is needed to typecast float to double when using e.g. fabs()? It is declared as double fabs(double x);

I haven't found anything in the compiler docs regarding this.

But even without typecasting, it compiles without warnings. By the way, the GCC compiles also without warnings when I mix up double with float.

1 Answers1

0

Numeric promotion

Whenever a value from one type is converted into a value of a larger similar data type, this is called a numeric promotion (or widening, though this term is usually reserved for integers). For example, an int can be widened into a long, or a float promoted into a double:

1 2 long l(64); // widen the integer 64 into a long double d(0.12f); // promote the float 0.12 into a double While the term “numeric promotion” covers any type of promotion, there are two other terms with specific meanings in C++:

Integral promotion involves the conversion of integer types narrower than int (which includes bool, char, unsigned char, signed char, unsigned short, signed short) to an integer (if possible) or an unsigned int. Floating point promotion involves the conversion of a float to a double. Integral promotion and floating point promotion are used in specific cases to convert smaller data types to int/unsigned int or double, because those data types are generally the most performant to perform operations on.

The important thing to remember about promotions is that they are always safe, and no data loss will result.

Source:

http://www.learncpp.com/cpp-tutorial/44-implicit-type-conversion-coercion/

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • First of, the question is tagged `c`, not `c++`. Second, much of this post is incomprehensible. – EOF Sep 07 '16 at 13:14
  • "and no data loss will result." --> Not always. Consider `fabs(LLONG_MAX)`. Conversion of wide integer types to FP types can often result in loss of precision (common) or even range in extreme cases like `(float) some_128_bit_int`. – chux - Reinstate Monica Sep 07 '16 at 13:58
  • integer to floating point promotion does not exist. The article is talking about small int to larger int and small float to larger float. not large int to large float which of course will not be correct all the time – Serve Laurijssen Sep 07 '16 at 16:26