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

C++ Tutorial - About Expressions and Statements

By David Bolton, About.com

5 of 8

Type Conversions in C++

In C, assignments were generally of the kind
lvalue = rvalue
Where lvalue means Left Value and rvalue means Right Value. A left value is the place where the result is stored and the rvalue is the value to be stored.

With C++ this isn't quite so simple. For instance is the result of a function an lvalue or a rvalue? If it is a reference then it's an lvalue, but anything else is an rvalue!

Type Conversions

The C++ compiler will implicitly convert or promote values if it can be done safely. If not it will generate a warning or an error depending on the conversion required.
const int big=110232343;
const short int small=big;
Will most likely generate a warning about truncation as trying to put a large number into a small variable will lose part of the number.

Promotion of Numeric Types

To make life simple, the compiler will make numbers bigger (never smaller) when evaluating expressions. If you add a float to a double, it will treat both as doubles. Add an int to a float and both are treated as floats. Add a short int to an int and both will be added as ints, and the same is true with char.
char a='2';
int b= a+ 9;
This is poor code but it compiles and runs. The implicit promotion of '2' to an int with a value of 50 results in it outputting 59. I've seen code in C like this and it is hard to understand and maintain.

Likewise with bools. Anything non zero is true while 0 is false. C didn't have the type bool, but C++ does and you should use it.

On the next page : Avoid mixing different types.

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

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Type Conversions in C++

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

All rights reserved.