From Matthew Probert · 1996-04-04 23:20 · #75207 in R25C
C CASTING
Matthew Probert
Servile Software
The C programming language is very flexible regarding the use of
different data types. Ints, longs, signed and unsigned and float types
can all be quite happily interchanged to completely screw up a
program!
Casting tells the C compiler what a data type is, and can be used to
change an expected data type to another. For example, consider the
following;
#include <stdio.h>
void main()
{
int x;
int y;
x = 10;
y = 3;
printf("\n%lf",x / y);
}
The printf() function has been told to expect a double. However, the
compiler sees the variables 'x' and 'y' as integers, and an error
occurs! To make this example work we must tell the compiler that the
result of the expression x / y is a double, this is done with a cast
thus;
#include <stdio.h>
void main()
{
int x;
int y;
x = 10;
y = 3;
printf("\n%lf",(double)(x / y));
}
Notice the data type 'double' is enclosed by parenthesis (this is
called casting), and so is the expression to convert. But now, the
compiler knows that the result of the expression is to be a double,
but it still knows that the variables 'x' and 'y' are integers and so
an integer division will be carried out. We have to cast the constants
thus;
#include <stdio.h>
void main()
{
int x;
int y;
x = 10;
y = 3;
printf("\n%lf",(double)(x) / (double)(y));
}
Because both of the constants are doubles, the compiler knows that the
outcome of the expression will also be a double.
... [Servile Info Journal]
___ Blue Wave/QWK v2.12
--- WILDMAIL!/WC v4.12
* Origin: Ooh! BBS, London [MULTILINES] 0181-395-3108 (2:254/233.0)