Hardware Reference
In-Depth Information
{
. . .
}
void foo (int abc) { . . . }
long soo (void) { . . . }
In fi le2:
int xy;
long arr[100];
5.9.3 Type Casting
Type casting causes the program to treat a variable of one type as though it contains data of
another type. The format for type casting is
(type) variable
For example, the following expression converts the variable kk to a long integer:
int kk;
. . .
(long) kk
Type casting can avoid many errors caused by size mismatch among operands. For example,
in the following program segment:
long result;
int
x1, x2;
. . .
result 5 x1 * x2;
if the product of x 1 and x 2 is larger than 2 16 2 1, it will be truncated to 16 bits. Then the vari-
able result will receive an incorrect value. To fi x the error, use type casting to force x 1 and x 2 to
long integers, as follows:
result 5 ((long) x1) * ((long) x2);
This technique is used in several examples in this text.
Another example of the use of type casting is in pointer type. Sometimes one needs to treat
the contents of a structure type variable as a string. The most convenient way to do it is to
recast the pointer to a structure-type variable into a pointer to a string (character type). For the
declarations
struct personal {
char name
[10];
char addr [20];
char sub1[5];
char sub2[5];
char sub3[5];
char sub4[5];
} ptr1;
char *cp;
we can use the following statement to treat the variable ptr 1 as a string:
cp 5 (char *) &ptr1;
 
Search WWH ::




Custom Search