50 likes | 74 Views
Department of Computer and Information Science, School of Science, IUPUI. A First C Program (mixing datatypes). Data Type Conversion. Rule #1 char, short int float double Rule #2 (double ← long ← unsigned ← int)
E N D
Department of Computer and Information Science,School of Science, IUPUI A First C Program (mixing datatypes)
Data Type Conversion • Rule #1 char, short int float double • Rule #2(double ← long ← unsigned ← int) • If either operand is double, the other is converted to double, and the result is double • Otherwise, if either operand islong, the other is converted tolong, and the result is long • Otherwise, if either operand is unsigned, the other is converted to unsigned, and the result is unsigned • Otherwise, the operand must beint
Examples Example: c: char, u: unsigned, i: int, d: double, f:float, s: short, l: long, Expression Final Data Type Explanation c – s / i intshortint, int/int, charint, int-int u * 3 – i unsignedint(3)unsigned, unsigned*unsigned=unsigned, intunsigned, unsigned-unsigned=unsigned u * 3.0 – i double unsigneddouble, double*double, intdouble, double-double=double c + i int charint c + 1.0 double charint (rule 1), intdouble(rule 2) 3 * s * l long shortint, int*int, intlong, long*long
Data Type Conversion (cont.) • Note: • Conversion of int to long preserves sign, so does short • Var = expr f = d;/* round off */ i = f; /* truncates fractions part, if the number is too big to fit, the result is undetermined */ i = l; s = i; and c = i; /* may eliminate high order bits */
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? */ • Unsigned int to int: there is not actual conversion between int and unsigned int. Example:(Assuming 2’s 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 */