Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between using floating point casts vs floating point suffixes in C and C++?

Is there a difference between this (using floating point literal suffixes):

float MY_FLOAT = 3.14159265358979323846264338328f; // f suffix
double MY_DOUBLE = 3.14159265358979323846264338328; // no suffix 
long double MY_LONG_DOUBLE = 3.14159265358979323846264338328L; // L suffix

vs this (using floating point casts):

float MY_FLOAT = (float)3.14159265358979323846264338328;
double MY_DOUBLE = (double)3.14159265358979323846264338328;
long double MY_LONG_DOUBLE = (long double)3.14159265358979323846264338328;

in C and C++?

Note: the same would go for function calls:

void my_func(long double value);

my_func(3.14159265358979323846264338328L);
// vs
my_func((long double)3.14159265358979323846264338328);
// etc.

Related:

  1. What's the C++ suffix for long double literals?
  2. https://en.cppreference.com/w/cpp/language/floating_literal
like image 695
Gabriel Staples Avatar asked Dec 04 '20 03:12

Gabriel Staples


Video Answer


1 Answers

The default is double. Assuming IEEE754 floating point, double is a strict superset of float, and thus you will never lose precision by not specifying f. EDIT: this is only true when specifying values that can be represented by float. If rounding occurs this might not be strictly true due to having rounding twice, see Eric Postpischil's answer. So you should also use the f suffix for floats.


This example is also problematic:

long double MY_LONG_DOUBLE = (long double)3.14159265358979323846264338328;

This first gives a double constant which is then converted to long double. But because you started with a double you have already lost precision that will never come back. Therefore, if you want to use full precision in long double constants you must use the L suffix:

long double MY_LONG_DOUBLE = 3.14159265358979323846264338328L; // L suffix
like image 89
orlp Avatar answered Sep 18 '22 23:09

orlp