Programming Tips: Assign Properly Typed Literals

Do you know the difference between the following two statements?

float myVal = 1.0;
float myVal = 1.0f;

If your best answer is: “There’s an ‘f’ after the 1.0,” then this tip is for you.

In C++, just as variables are of particular types, so is the case with the literals (the actual numbers) that you assign to them. By matching the types of your literals with the types of the variables to which you assign them, you can save yourself the cost of implicit casts from one data type to another that occur when you assign literals with a mismatched type. It’s an admittedly small benefit, but also a no-brainer, so it’s worth making a habit.

Here’s the list of the usual suspects and their subscripts:

int myInt = 10;
unsigned int myUnsignedInt = 10U;

long myLongInt = 10L;
unsigned long myUnsignedLongInt = 10UL;

float myFloat = 10.0f;
double myDouble = 10.0;
long double myLongDouble = 10.0L;
Check here for more articles in this series: Game Development
  • Language

  • Sponsored Links

  • Rob's Portfolio

    Games Writing Contributions

No comments yet.

Leave a comment