A First C Program (Mixing Datatypes) : Department of Computer and Information Science, School of Science, IUPUI
A First C Program (Mixing Datatypes) : Department of Computer and Information Science, School of Science, IUPUI
A First C Program
(mixing datatypes)
Dale Roberts
Data Type Conversion
Rule #1
char, short int
float double
Dale Roberts
Examples
Example: c: char, u: unsigned, i: int, d: double, f:float,
s: short, l: long,
Dale Roberts
Data Type Conversion (cont.)
Note:
1. Conversion of int to long preserves sign, so does short
2. Var = expr
f = d; /* round off */
i = f;
/* truncates fractions part, if the number is too big to fit, the result is
undetermined */
Dale Roberts
3. If a specific type is required, the following syntax may be used,
called cast operator.
(type) expr
Example:
float f=2.5;
x = (int)f + 1;
/* the result is 3, Q: will f value be changed? */
4. Unsigned int to int:
there is not actual conversion between int and unsigned int.
Example:(Assuming 2s complement machine and int is 2 bytes long)
unsigned i = 65535; int j;
j = i; /* j will be 1 */
j = -2;
unsigned i = 1 + j; /* i= 65535 */
Dale Roberts