1

In my source code, if I write 1.23 as a literal, e.g. doThis(1.23), gcc assumes it's a double.

Rather than type doThis((float) 1.23), is there a way to use floats for decimal literals/constants unless otherwise specified in an individual source file?

Mega-bonus points, is there a way that works across (nearly) every C compiler?

HoboBen
  • 2,900
  • 4
  • 21
  • 26
  • There's no way to do it for all "plain" constants in a source file, as you seem to want. You have to use either a cast or a suffix. – AnT stands with Russia Oct 11 '10 at 06:34
  • The suffix works great... I'd completely forgotten about it! – HoboBen Oct 11 '10 at 06:38
  • [Make C floating point literals float (rather than double)](https://stackoverflow.com/q/32266864/995714). But note that this is not recommended for most cases – phuclv Sep 10 '18 at 17:20

4 Answers4

7

Yes, the standard way is to write 1.23f. It works with every C compiler, since it is defined in ISO C99 section 6.4.4.2 Floating constants. ISO C90 and K&R have similar definitions.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
5

try:

float fred = 0.37f;
Bas Bossink
  • 9,388
  • 4
  • 41
  • 53
2

try 123.4F for a float constant

Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
2

Also gcc has the option -fsingle-precision-constant that tells the compiler to treat constants as single precision. See http://gcc.gnu.org/wiki/FloatingPointMath

Paul Beusterien
  • 27,542
  • 6
  • 83
  • 139