Friday, 6 February 2009

Helping C++ compilers determine literal types

A little while back I was looking around for some coding standards to improve my work. I stumbled upon some id Software C++ Coding Conventions which were quite useful, especially the comments about using "const" as much as possible. Also have a look at the comments, especially about the book,“C++ Coding Standards” by H. Sutter et al, Addison-Wesley, Feb 2005.

Another recommendation that puzzled me was using the suffix "f" when specify floats. For example, 0.0f instead of just 0.0. For the longest while, I just did it but it occured to me that perhaps I should do this for other numbers too. I looked what I should do for integers, doubles and so on.

There are only a few situations where doing this is useful. Those situations are for:
  • long int, 35000L
  • unsigned int, 10000U
  • unsigned long, 12323UL
  • floats, 1.0f
  • long double, 1001.2L
The reason you would want to do this is to use the less expensive data type when possible. A float is less expensive than a double. By adding the a suffix, this helps the compiler determine whether a number is a float or a double.

See for page 55, under the topic Literals in "C++: A Beginner's Guide" by Herbert Schildt, Edition: 2, Published by McGraw-Hill Professional, 2003 for more details. The book is also available on Google Books.

No comments:

Post a Comment