Programming in C

(Barry) #1
Data Type Conversions 327

Here’s a function called distancethat calculates the distance between two points.

#include <math.h>


double distance (Point p1, Point p2)
{
double diffx, diffy;


diffx = p1.x - p2.x;
diffy = p1.y - p2.y;

return sqrt (diffx diffx + diffy diffy);
}


As previously noted,sqrtis the square root function from the standard library. It is
declared in the system header file math.h, thus the reason for the #include.
Remember, the typedefstatement does not actually define a new type—only a new
type name. So the Countervariables jand n, as defined in the beginning of this section,
would in all respects be treated as normal intvariables by the C compiler.


Data Type Conversions


Chapter 4, “Variables, Data Types, and Arithmetic Expressions,” briefly addressed the fact
that sometimes conversions are implicitly made by the system when expressions are eval-
uated.The case you examined was with the data types floatand int.You saw how an
operation that involved a floatand an intwas carried out as a floating-point opera-
tion, the integer data item being automatically converted to floating point.
You have also seen how the type cast operator can be used to explicitly dictate a con-
version. So in the statement


average = (float) total / n;


the value of the variable totalis converted to type floatbefore the operation is per-
formed, thereby guaranteeing that the division will be carried out as a floating-point
operation.
The C compiler adheres to strict rules when it comes to evaluating expressions that
consist of different data types.
The following summarizes the order in which conversions take place in the evalua-
tion of two operands in an expression:



  1. If either operand is of type long double, the other is converted to long double,
    and that is the type of the result.

  2. If either operand is of type double, the other is converted to double, and that is
    the type of the result.

  3. If either operand is of type float, the other is converted to float, and that is the
    type of the result.

Free download pdf