|
Lesson 11:
Typcasting
Admitedly, typecasting is not a huge part of C or C++
programming. However, there are times
when it is actually the best, or perhaps only, way to
accomplish something. Typecasting is
basically turning a variable of one type, say an int,
into another type, a char, for one a single
application.
Typecasts look like a data-type, like int, in between
two parentheses. (char)aninteger will
interpreted as a character for purposes of the function.
For example:
#include <iostream.h>
//For cout
void main()
{
cout<<(char)65; //The (char) is a type cast, telling the
computer to interpret the 64 as a
//character, not as a number. It is going to give the
ASCII output of the
//equivalent of the number 64(It should be the letter
A).
}
One use of typecasting is when you want to use the ASCII
characters. For example, what if
you want to create your own chart of all 255 ASCII
characters. To do this, you will need to use
a typecast to allow you to print out the integer as a
character.
#include <iostream.h>
#include <conio.h>
void main()
{
for(int x=1; x<256; x++) //The ASCII character set is
from 1 to 255
{
cout<<x<<". "<<(char)x<<" "; //Note the use of the int
version of x to output a number
//and the use of (char) to typecast the x into a
character
//which outputs the ASCII character that corresponds to
the
//current number
}
getch();
}
You can make a version of this program that will allow
the user to enter a number, and the
program could give the user the character corresponding
to the number.
Typecasting is more useful than this, but this was just
an introduction. Admittedly, not
the most advanced lesson, but one that can be very
useful none-the-less.
|