Conversions    
 
  Constantes 
 
  Kepler's laws  
 
  Unités  
 
  ask us  
 


Coding &
programming


Installing CodeBlocs compiler

C language


C++ language




© The scientific sentence. 1998-2016 
 

Programming with C/C++ Language
Typecasting in C and C++





1. The C style casting


Typecasting is making a variable of one type act like another type.

To typecast something, simply put the type of variable inside parentheses in front of the actual variable.

Here is an example:

(char)65

The (char) is a typecast, telling the computer to interpret 65 as a character, not as a number.

We use typecasting when yusing the ASCII characters. For example, what if you want to create your own chart of all 128 ASCII characters.

To do this, you will need to use to typecast to allow you to print out the integer as its character equivalent.

The following code:

for ( int x = 0; x < 128; x++ ) {
cout << x << ". "<< (char)x << " ";
}

Will use the int to output a number and the (char) to typecast the x into a character which outputs the ASCII character that corresponds to the current number.


2. The C++ style casting


The typecast described above is a C style cast, C++ supports two other types. First is the function-style cast:

char ( 78 )

This is more like a function call with its argument. Next is :

static_cast ( 78 )

It exist also three other types of named casts : const_cast, reinterpret_cast, and dynamic_cast.


3. When to use typecast


One use of typecasts is to force the correct type of mathematical operation to take place.

Note that in C and C+, and other programming languages, the result of the division of integers is itself treated as an integer:

For instance, 2/3 becomes 0, because 2/3 is less than 1, and integer division ignores the remainder.


Division between floating point numbers, or even between one floating point number and an integer keeps the result as a floating point number.

For instance, static_cast(2)/5 comes out to .4, as wewould expect.








  

Google
  Web ScientificSentence
 


chimie labs
|
scientific sentence
|
java
|
php
|
green cat
|
contact
|


© Scientificsentence 2009. All rights reserved.