1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Handling Ints and Floats

By , About.com Guide

7 of 8

Things to Watch out for with ints, floats and bools

Take a look at this statement.
float f = 122/11;
You'd expect something like a value of 11.0909090909. In fact the value is 11. Why is this? because the expression on the right hand side (known as an rvalue) is integer/integer. So it uses integer arithmetic which throws away the fractional part and assigns 11 to f. Changing it to

float f = 122.0/11
will correct it. It's a very easy gotcha.

Types Bool and Int

In C, there is no such type as a bool. Expressions in C were based on a zero being false or a non zero being true. In C++ the type bool can take the values true or false. These values are still equivalent to 0 and 1. Somewhere in the compiler it will have a
const int false=0;
const int true= 1;
Or at least it acts that way! The two lines below are valid without casting so behind the scenes, bools are implicitly converted to ints and can even be incremented or decremented though this is very bad practice.
bool fred=0;
int v = true;

Look at this code

bool bad = true;
bad++
if (bad) ...
The if will still do the if as the bad variable is non zero but it is bad code and should be avoided. Good practice is to use them as they are intended. if (!v) is valid C++ but I prefer the more explicit if (v != 0). That however is a matter of taste, not a must-do directive.

On the Next Page - Learn to use Enums

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Things to Watch Out For with ints, floats and bools

©2009 About.com, a part of The New York Times Company.

All rights reserved.