Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make C floating point literals float (rather than double)

It is well known that in C, floating point literals (e.g. 1.23) have type double. As a consequence, any calculation that involves them is promoted to double.

I'm working on an embedded real-time system that has a floating point unit that supports only single precision (float) numbers. All my variables are float, and this precision is sufficient. I don't need (nor can afford) double at all. But every time something like

if (x < 2.5) ... 

is written, disaster happens: the slowdown can be up to two orders of magnitude. Of course, the direct answer is to write

if (x < 2.5f) ... 

but this is so easy to miss (and difficult to detect until too late), especially when a 'configuration' value is #define'd in a separate file by a less disciplined (or just new) developer.

So, is there a way to force the compiler to treat all (floating point) literals as float, as if with suffix f? Even if it's against the specs, I don't care. Or any other solutions? The compiler is gcc, by the way.

like image 958
Zeus Avatar asked Aug 28 '15 08:08

Zeus


People also ask

Can I use float instead of double?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float. For example, to store the annual salary of the CEO of a company, double will be a more accurate choice.

Should I use float or double in C?

The default choice for a floating-point type should be double . This is also the type that you get with floating-point literals without a suffix or (in C) standard functions that operate on floating point numbers (e.g. exp , sin , etc.).

What is the difference between floating-point literal and double type literal?

Answer. float literals have a size of 32 bits so they can store a fractional number with around 6-7 total digits of precision. double literals have a size of 64 bits so they can store a fractional number with 15-16 total digits of precision.


1 Answers

-fsingle-precision-constant flag can be used. It causes floating-point constants to be loaded in single precision even when this is not exact.

Note- This will also use single precision constants in operations on double precision variables.

like image 82
ameyCU Avatar answered Nov 07 '22 20:11

ameyCU