MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Typecast Operator

We have seen in the previous sections and last unit that when constants and variables of different types are mixed in an expression, they are converted to the same type. That is automatic type conversion takes place. The following type conversion rules are followed:

  1. All chars and short ints are converted to ints. All floats are converted to doubles.
  2. In case of binary operators, if one of the two operands is a long double, the other operand is converted to long double,
    else if one operand is double, the other is converted to double,
     else if one operand is long, the other is converted to long,
     else if one operand is unsigned, the other is converted to unsigned 

C converts all operands “up” to the type of largest operand (largest in terms of memory requirement for e.g. float requires 4 bytes of storage and int requires 2 bytes of storage so if one operand is int and the other is float, int is converted to float).

All the above mentioned conversions are automatic conversions, but what if int is to be converted to float. It is possible to force an expression to be of specific type by using operator called a cast. The syntax is as follows:

(type) expression

where type is the standard C data type. For example, if you want to make sure that the expression a/5 would evaluate to type float you would write it as

( float ) a/5

cast is an unary operator and has the same precedence as any other unary operator.  
 

Report an issue

Reporting: Typecast Operator (topic)

Related Posts