C does not enforce types strictly: it is a wekly-typed language. It is quite in order to use mixed mode operations (mixing diferent types), but you need to be sure how things work out.
Some things happen sensibly:
double speed; int i; i= 30; speed= i;
has a fairly clear interpretation.
Similarly, calling a function which has a double argument, but using an integer value, is interpreted correctly (because the value is basically assigned to the dummy argument).
Also
x= 5 * 6.7;
The RHS contains an integer constant and a real constant.
What happens is implicit conversion: the 5 is treated as a real number ("5.0") and then floating point multiplication is used.
If the LHS (x) is a real, the answer is simply assigned.
If it is an integer, the value is converted to integer and that is assigned.
In general, when a binary operator is given two types, the lower type is promoted to the higher before the calculation is performed:
In fact it is good practice, and often essential, to coerce the types using one of the cast operators.
Example
We might have written:
speed= (double) i;or
x= (int) ( 5.0 * 6.7 );or even
x= (int) ( (double) 5 * 6.7 );
In general we can force a change of type with a cast operator, where the latter is any type name, including that of a user-defined type, enclosed in brackets.
Note however that all C floating point arithmetic is performed at double precision, regardless, with implicit conversion where needed.
Notes
1. Be careful to get exactly the effect you want:
(double) (4 * 3 / 7)
produces the answer 1.0, because the arithmetic is all performed in integer form and the truncated answer is then converted to double.
2. When converting chars to ints, there are two ways this might be done and the result is therefore machine dependent. Some machines simply put zeroes in the top bits of the int, thus giving a positive number. Others will sign extend the top bit so that chars with a leading 1 will become negative integers.
The reverse operation (int to char) is well-behaved: the excessive high-order bits are simply thrown away.
3. You can coerce anywhere a value might be needed. Thus the library routine sqrt needs a double argument; if you have an integer n, you may write:
sqrt( (double) n )
4. Note that coercion only affects the value being used in the expression, not the variable which has been cast (in the previous example, this does not change n itself).
maspjw@